首页 > 解决方案 > 从 JS 到 PHP 的 AJAX POST 是空的

问题描述

索引.html:

<script>
 function myFunction() {
        var srcd = document.getElementById("two").src;
        $.ajax({
          type: "POST", //type of method
          url: "/file.php", //your page
          data: {
            src: srcd
          }, // passing the values
          success: function(res) {
            location.reload(); 
          }
        });
      }
</script>

文件.php:

<?php
header('Access-Control-Allow-Origin: *');
$src = $_POST["src"];
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode( $jsonString, true );
foreach ( $data as $key => $entry )
{
        if ( $entry['src'] == $src )
        {
                $data[$key]['counter']++;
        }
}
$newJsonString = json_encode( $data );
file_put_contents( 'jsonFile.json', $newJsonString );
?>

但是我已经意识到$src在 PHP 中是空的。变量没有赋值。我知道 POST 请求发生的事实,好像访问控制标头不存在于file.php中,控制台中出现错误。

如果我直接为 PHP 文件分配一个值并运行它,比如$src = 'https://someurl.com/';,它会按预期工作。

我怎样才能解决这个问题?

谢谢。

标签: javascriptphpajaxpost

解决方案


推荐阅读