2017-07-07 68 views
0

我使用ajax发送请求到一个php页面,该页面设置一个cookie并使用echo函数将消息发送回浏览器。但问题是,PHP成功设置cookie,但我没有收到消息回声。 我已经在控制台上记录了XMLHTTPRequest对象来确认。Ajax和PHP - 意外行为

这里是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. 
    } 
    ?> 

这个responseText然而,这不是不确定的,这是一个空字符串。看看图片。 Chrome Dev Tools.

+0

用'echo json_encode('true)替换'echo“true”;'' –

+1

没有足够的信息。我相信你期待JSON格式的响应。但是,我们仍然不知道您打印的是什么。 – tilz0R

+0

你的if语句没有执行... init参数不会与http请求一起发送ajax代码 –

回答

0

发现问题,感谢您的帮助,伙计们。

我在做的事情是将json数据字符串化并将其作为普通的post请求发送并期望它可以正常工作,但它没有出于某种原因。

我写了一个函数,向服务器发送一个post请求。

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. 

我认为这将是初始化字符串帖子发送请求,然后我可以用$ _ POST访问字符串[“初始化”],并在其上使用json_decode。但由于某种原因,有效载荷仅包含stringyfied json(使用Chrome Dev Tools进行检查),所以现在我们必须使用$ _POST [0]来访问它,即访问post数组的第一个元素,然后解析它。 Post现在不是一个关联数组(idk为什么)。

感谢评论:) 爱情stackoverflow。