繁体   English   中英

使用POST方法从javascript向服务器发送json数据的问题

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

我试图看到我使用XMLHttpRequest发送到服务器的json数据,但似乎服务器没有收到它,当我运行javascript时,警报窗口将弹出但不打印任何内容。 有谁知道如何解决这个问题? 谢谢

在客户端,Java脚本

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);

在服务器上,PHP

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

James的解决方案工作正常,但如果您希望使用application / json内容类型发送数据,则必须以不同的方式访问数据。

对于你有服务器端,

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

改变这个(就像詹姆斯那样):

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

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

如果您想使用application / json内容类型,那么您必须更改访问服务器端的方式:

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

您正在发送JSON数据,但内容类型设置为application/x-www-form-urlencoded 您应该发送表单/编码数据( var obj="action=nothing" )或将content-type设置为JSON( application/json

这对我有用:

<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>

暂无
暂无

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

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