[英]JSON POST from Javascript to PHP
I am trying to send a JSON string by Javascript to a PHP script. 我正在尝试通过Javascript将JSON字符串发送到PHP脚本。 Unfortunately it is empty.
不幸的是它是空的。 I have already checked a hundred sites on Google and SO, but I cannot find a solution to the problem.
我已经在Google和SO上检查了一百个站点,但是找不到解决该问题的方法。 Here is what I am doing:
这是我在做什么:
My HTML/Javascript: 我的HTML / Javascript:
<head>
<script type="text/javascript">
function button1_Click() {
var url = 'http://192.168.2.105/testpost.php';
var method = "POST";
var postData = {
"first": "John",
"last": "Doe"
};
var xhr = new XMLHttpRequest();
xhr.open( 'POST', url );
xhr.setRequestHeader( 'Content-Type', 'application/json' );
xhr.send( JSON.stringify(postData) );
}
</script>
</head>
<body>
<button id="button1" onclick="button1_Click()">Print</button>
</body>
And my PHP: 而我的PHP:
<?php
ob_start();
var_dump($_REQUEST);
file_put_contents('test.txt', ob_get_contents());
ob_end_close();
?>
And this is what I'm getting in test.txt: 这就是我在test.txt中得到的:
array(0) {
}
I have no idea, why this is empty. 我不知道为什么这是空的。 Can you please help?
你能帮忙吗?
Edit: Thanks to Edgar Villegas Alvarad and Quentin 编辑:感谢埃德加·维尔加斯·阿尔瓦拉德和昆汀
In HTML I changed the following: 在HTML中,我更改了以下内容:
xhr.setRequestHeader( 'Content-Type', 'text/plain' );
Then in PHP: 然后在PHP中:
<?php
$json_data = json_decode($HTTP_RAW_POST_DATA);
ob_start();
echo $json_data->first;
file_put_contents('test.txt', ob_get_contents());
ob_end_close();
?>
And finally I get in test.txt: 最后我进入test.txt:
John
That was what I needed. 那就是我所需要的。
In this case, you have to send your params url encoded. 在这种情况下,您必须发送经过网址编码的params。 So instead of this:
所以代替这个:
xhr.send( JSON.stringify(postData) )
do this: 做这个:
xhr.send( "postData=" + encodeURIComponent(JSON.stringify(postData)) );
Then in php you read it with: 然后在php中阅读:
$postData = json_decode($_POST['postData']);
EDIT , Oh, I saw you're sending as application/json
. 编辑 ,哦,我看到您是作为
application/json
发送的。 In that case you are sending it correctly and you should read it like this: 在这种情况下,您可以正确发送它,应该这样阅读:
$postData = json_decode($HTTP_RAW_POST_DATA);
$HTTP_RAW_POST_DATA
gets the body of the request, exactly what you need. $HTTP_RAW_POST_DATA
获取请求的主体,正是您所需要的。 I hope it's available in your php env. 我希望它在您的php env中可用。 If it's not, you can use
file_get_contents("php://input")
( info ). 如果不是,则可以使用
file_get_contents("php://input")
( info )。
Hope this helps. 希望这可以帮助。 Cheers
干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.