PHP 通过 curl_exec 执行有 Ajax 请求无效

PHP execute via curl_exec have Ajax request which is not working

我举例说明了我的问题。 我有 4 个文件

  1. index.php
  2. RunViaAjax.php
  3. SendRequest.php
  4. AjaxFile.php

index.php 文件

<!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    </head>
    <body>

        <button id="OK">Test Ajax</button>

       <script> 
    $("#OK").click(function(){
        $.ajax({
            type: "POST",
            url: 'RunViaAjax.php',
            data: {data: "someData"}, // serializes the form's elements.
            success: function(data){
                console.log(data);
            }
        });
    }); 
        </script>
    </body>
</html>

RunViaAjax.php 文件

<?php

    $curl = curl_init();
    // Set some options - we are passing in a useragent too here
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'http://localhost/tester/SendRequest.php',
        CURLOPT_USERAGENT => 'Codular Sample cURL Request'
    ]);
    // Send the request & save response to $resp
    $resp = curl_exec($curl);
    echo $resp;
    // Close request to clear up some resources
    curl_close($curl);

?>

SendRequest.php 文件

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

</head>
<body>
    <p id="result"></p>
    <script> 
    $.ajax({
      type: "POST",
      url: 'AjaxFile.php',
      data: {data: "someData"}, // serializes the form's elements.
      success: function(data){
        $('#result').html(data);
      }
    });

    </script>
</body>
</html>

AjaxFile.php 文件

<?php 

    file_put_contents("OK-Report.php", "");
    echo "OK REPORT";

?>

现在 运行 宁 index.php,正在获取 SendRequest.php 的源代码。 我需要的是 运行 SendRequest.php (SendRequest.php 是动态创建的文件)。

希望对您有所帮助。

File1.php

$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://localhost/test/MyFile.php',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request'
]);
// Send the request & save response to $resp
$resp = curl_exec($curl);
print_r($resp);
// Close request to clear up some resources
curl_close($curl);

MyFile.php

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

</head>
<body>

    <p id="result"></p>
   <script> 
    $.ajax({
           type: "POST",
           url: 'AjaxFile.php',
           data: {data: "someData"}, // serializes the form's elements.
           success: function(data)
           {
            $('#result').html(data);
           }
         });

    </script>
</body>
</html>

AjaxFile.php

<?php echo 'Ajax request recieved' ?>