简体   繁体   English

Ajax和PHP-意外行为

[英]Ajax and PHP - unexpected behaviour

I'm using ajax to send a request to a php page which sets a cookie and sends a message back to the browser using the echo function. 我正在使用ajax将请求发送到php页面,该页面设置cookie并使用echo函数将消息发送回浏览器。 But the problem is that php sets the cookie successfully but I don't get the message in echo. 但是问题是php成功设置了cookie,但是我没有在echo中收到消息。 I've console logged the XMLHTTPRequest Object to confirm that. 我已经在控制台上记录了XMLHTTPRequest对象以确认这一点。

Here's the php code : 这是php代码:

    <?php header("Access-Control-Allow-Origin: *");
    session_start();
    // echo "true"; - If I put the echo here , I get the response.
    if(isset($_POST['init'])){
        $x00 = universe::decode($_POST['init']);// Just a static function call of object Universe.
        $_SESSION['id'] = $x00['id'];
        echo "true"; // This echo does not appear in the response.
    }
    ?>

The responseText is however not undefined , it's an empty string. 但是responseText不是undefined,它是一个空字符串。 Take a look at the Pic. 看看Pic。 Chrome开发工具。

Found the problem , thanks for helping, guys. 找到了问题,谢谢大家的帮助。

What I did intinally was stringify the json data and sent it as a normal post request and expected it to work , but it didn't for some reason. 我本来要做的是将json数据字符串化,并作为普通的发帖请求发送并期望它能正常工作,但是由于某种原因,它没有。

I wrote a function that sends a post request to the server. 我编写了一个函数,该函数将发布请求发送到服务器。

ajax.send(x); //Send is a function of the object ajax , x is the payload.

param = {"id": "qbcd"} //json data
param=JSON.stringify(ajax.param); // converted to string.
ajax.send("init="+param); // This will send a post request to the server.

I thought it will send the post request with init being a string and then I can access the string with $_POST['init'] and use json_decode on it . 我以为它将发送init为字符串的post请求,然后可以使用$ _POST ['init']访问该字符串并在其上使用json_decode。 But for some reason the payload contains the stringyfied json only( checked it with Chrome Dev Tools) , so now we have to access it with $_POST[0] ie, access the first element of the post array and then parse it . 但是由于某种原因,有效负载仅包含经字符串解析的json(已通过Chrome开发工具进行了检查),因此现在我们必须使用$ _POST [0]访问它,即访问post数组的第一个元素,然后对其进行解析。 Post is now not an associative array ( idk why). 现在,Post不是关联数组(为什么是idk)。

Thanks for commenting :) Love stackoverflow. 感谢您的评论:)喜欢stackoverflow。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM