dptpn06684 2013-05-21 18:53
浏览 71

AJAX向PHP发送变量无法正常工作

var xmlhttp;
if (window.XMLHttpRequest) {
    xmlhttp=new XMLHttpRequest();
}
else {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("POST","test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("abc=123");

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {

        <?php if(isset($_POST['abc'])) {
            $test123 = 'worked';
        }
    ?>

}}
var worked = '<?php echo $test123;?>'; // <--- this is not working

How can I make this work? I don't receive the variable in PHP whether I use get or post methods.

  • 写回答

2条回答 默认 最新

  • dpruwm6206 2013-05-21 18:58
    关注

    You seem to have two fundamental misunderstandings. One is about AJAX, and the other is about client side vs. server side code. The latter is more important.

    Server vs. Client

    Essentially PHP and JavaScript are totally agnostic to each other. They do not run in parallel. In this context, they don't even run on the same machine (the PHP code runs on your server, the JavaScript on the user's computer). The only communication each script can do with the other is via HTTP.

    It's test.php that needs to have the code

    <?php if(isset($_POST['abc']))
    {
    $test123 = 'worked';
    }
    ?>
    

    As long as test.php exists, this should work, but I'm thinking of it as a standalone script.

    Using AJAX

    Because of the asynchronous nature of AJAX and its HTTP dependency, you can't rely on when an ajax request will complete or even if it will complete. That is to say that any code that depends on the result of an AJAX call must be done in the ajax response callbacks.

    That is, you would do something like this:

    //php
    <?php if (isset($_POST['abc']) { echo json_encode(array('success' => true)); }
    
    //JavaScript
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        if (JSON.parse(xmlhttp.responseText).success) {
            console.log('it worked!');
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大