开发者

Problems with sending json data to server from javascript using the POST method

I am trying to see the 开发者_Go百科json data I sent to the server using XMLHttpRequest but it seems that the server is not receiving it, when I run the javascript the alert window will pop up but doesn't print anything. Anyone know how to solve this problem? Thanks

On the client side, Java script

var obj = {"action": "nothing"};

var jsonString = "jsonString=" + JSON.stringify(obj);


var xmlhttp = new XMLHttpRequest();

xmlhttp.open("POST","http://myserver/main.php",true);

xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.setRequestHeader("Content-Length",jsonString.length);

xmlhttp.onreadystatechange = function() 
{           
      if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
          alert(xmlhttp.responseText);
      }
}
xmlhttp.send(jsonString);

On the server,php

if(isset($_POST['jsonString'])) 
echo $_POST['jsonString'];


You're sending JSON data, but the content-type is set to application/x-www-form-urlencoded. You should either send form/encoded data (var obj="action=nothing") or set the content-type to JSON (application/json)


James' solution works just fine, but if you are looking to send data using the application/json content type then you have to access the data in a different way.

For what you have server side,

if(isset($_POST['jsonString'])) 
echo $_POST['jsonString'];

change this (like James did):

xmlhttp.setRequestHeader("Content-type","application/json");

to

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

IF YOU WOULD LIKE TO USE THE application/json content type then you must change how you access it server side with:

    $json_string = file_get_contents('php://input');
    $json_object = json_decode($json_string); 
    echo $json_object->action;


This is working for me:

<html>
<head>
<script src='json.js'></script>
</head>
<body>

<script>
var obj = {"action": "nothing"};
var jsonString = "jsonString=" + JSON.stringify(obj);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","whereIPutThePHP.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-Length",jsonString.length);

xmlhttp.onreadystatechange = function() 
{           
      if(xmlhttp.readyState === 4 && (xmlhttp.status === 200)){
          alert(xmlhttp.responseText);
      } 
}
xmlhttp.send(jsonString);
</script>

</body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜