我遇到了这个问题,我的Ajax JSON.stringify的一部分以文本的形式到达,另一部分类似于数组元素,我的问题是如何将所有内容转换为数组并提取元素值,下面是我在我的PHP脚本中接收到的代码:
array (size=3)
'JSON' => string ' {
"requestType":"TourListRequest",
"data":{
"ApiKey":"12345",
"ResellerId":"1000",
"SupplierId":"1004",
"ExternalReference":"10051374722994001",
"Timestamp":"2013-12-10T13:30:54.616+10:00",
"Extension":{
"any":{
}
},
"Parameter":{
"Name":{
"0":" "
},
"Value":{
}
}
}
}
' (length=412)
'URL' => string 'api_test_json.php?test=JSON Tour List' (length=37)
'Type' => string 'JSON Tour List' (length=14)
我的问题是:如何获得"requestType“、"ApiKey”、"ResellerId“等作为PHP变量的值?
这是我生成AJAX调用的代码:
<textarea style="width: 100%; height: 300px;" id="request_json">
{
"requestType":"TourListRequest",
"data":{
"ApiKey":"12345",
"ResellerId":"900",
"SupplierId":"904",
"ExternalReference":"10051374722994001",
"Timestamp":"2013-12-10T13:30:54.616+10:00",
"Extension":{
"any":{
}
},
"Parameter":{
"Name":{
"0":" "
},
"Value":{
}
}
}
}
<script>
function SubmitAPI(){
var sendInfo = { JSON: $('#request_json').val(),
URL: $('#supplier_api_endpoint_JSON_Tour_List').val(),
Type: 'JSON Tour List' };
$('#response_json').html("Calling API...");
$.ajax({
url: "post_JSON.php",
data: {data: JSON.stringify(sendInfo)},
dataType: 'html',
type: "POST",
cache: false,
success: function(data){
console.log(data)
$('#response_json').html(data);
}
});
}
</script>
谢谢你提前..。
发布于 2014-04-06 21:22:12
您只需解码JSON并访问结果对象数据中的变量。
$array = ...; // the array you dump in your example
$obj = json_decode($array['JSON']);
// request type information
$request_type = $obj->requestType;
// here is all the stuff in 'data'
$data = $obj->data;
// now access your data variables like
echo $data->ApiKey;
echo $data->ResellerId;
// and so on...
这里大部分工作都是由json_decode()
步骤完成的。JSON只是对象和/或数组数据的序列化方法。一旦您通过json_decode()
反序列化它,您就可以直接访问任何被序列化成JSON的数据结构,就像任何普通的数字索引数组或stdClass
对象(PHP的默认对象类型)一样。
注意,在使用此函数时,经常会看到true
作为第二个参数传递。这将JSON对象结构转换为关联数组,而不是stdClass
对象。我个人很少使用这种方法,因为在很多情况下,对象结构{}
中的项应该更多地作为PHP中的对象来处理,而不是更像映射的关联数组。然而,由于某些原因,在PHP中工作的人更倾向于使用关联数组,因此您将在很多例子中看到这一点(比如json_decode($json, true)
)。
https://stackoverflow.com/questions/22900117
复制相似问题