[英]Unable to get JSON from Ajax POST using PHP
I am sending JSON in a POST to my PHP script. 我正在POST中将JSON发送到我的PHP脚本。 I'm unable to get the object values from the JSON.
我无法从JSON获取对象值。 The format of the POST is as follows:
POST的格式如下:
[{"name":"amount","value":"12"}]
[{“ name”:“ amount”,“ value”:“ 12”}]
Javascript Java脚本
("#idForm").submit(function(e) {
var url = "post.php"; // the script where you handle the form input.
var formData = JSON.stringify($("#idForm").serializeArray());
alert(formData);
$.ajax({
type: "POST",
url: url,
data: formData,
dataType: 'json',
success: function(dataresponse) {
document.getElementById("orderamount").innerHTML = dataresponse.orderamount;
}
});
PHP 的PHP
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$data = array();
$json = json_decode(file_get_contents('php://input'), true);
$data['orderamount'] = $json['amount'];
//this works
//$data['orderamount'] = '12345';
echo json_encode($data);
}
Any idea what I'm doing wrong? 知道我在做什么错吗?
We can parse JSON Array, and dictionaries inside it, like this, 我们可以解析JSON Array及其内部的字典,就像这样,
<?php
$json = "[{\"name\":\"amount\",\"value\":\"12\"}]";
$dec = json_decode($json,true);
for($idx = 0; $idx < count($dec); $idx++){
$obj = (Array)$dec[$idx];
echo $obj["name"];
}
?>
In your example json there are two parameters, name and value. 在示例json中,有两个参数,名称和值。
[{"name":"amount","value":"12"}]
[{“ name”:“ amount”,“ value”:“ 12”}]
You should use $json['name']
instead of $json['amount']
. 您应该使用
$json['name']
而不是$json['amount']
。 You can try the following example 您可以尝试以下示例
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$data = array();
$json = json_decode(file_get_contents('php://input'), true);
if($json['name']=='amount') {
$data['orderamount'] = $json['value'];
}
echo json_encode($data);
}
请在发送请求之前尝试
setRequestHeader("Content-type", "application/x-www-form-urlencoded");
In Response 作为回应
document.getElementById("orderamount").innerHTML = dataresponse['orderamount']; document.getElementById(“ orderamount”)。innerHTML = dataresponse ['orderamount'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.