PHP 帖子无法使用标头和 Ajax

php post not working using header and ajax

本文关键字:Ajax PHP      更新时间:2023-09-26

我正在使用jQuery $.post向另一个域发送POST请求。 一切都很好,但我没有在请求的页面中获取发布的数据,请检查我的代码

j查询代码

    var data = {mydata: 'testing'};
      $.post("http://anyurl/file.php",data,function(info){
        alert(info);
    });

这是PHP代码

<?php
header('Access-Control-Allow-Origin: *'); // this is to allow another domain
$data = $_POST[“mydata”]; // assigning data to variable
echo $data; // sending back to jquery
?>

它不返回数据请检查任何人。

提前致谢

使用 proper quotes 并使用 isset() 检查data设置与否,

<?php
    header('Access-Control-Allow-Origin: *'); // this is to allow another domain    
    print_r($_POST);// to check the post data
    $data = isset($_POST['mydata']) ? $_POST['mydata'] : "No Data";
    echo $data; // sending back to jquery
?>

尝试获取带有single quotes的 POST 变量,最好回显后放置exit

$data = $_POST['mydata'];
echo $data; 
exit;

并确保它是否通过console发布到给定的 URL。

好的,当我测试它时它走得很好。为了重新出现您遇到的错误,我正在尝试将文件.php设置为 BOM-UTF8 文件,最终出现错误。So,please check your file.php if it got a BOM before header().

另一个建议是,你可以使用Firebug来测试你的ajax后期进程。控制台中的链接将显示 ajax 进程,例如您发布的内容和反馈。只需使用 console.log() 而不是 alert()。