用var_dump回显解码数组时遇到问题。单击每一行的按钮后,一个唯一的xmlhttprequest,然后执行一个ajax调用理论,但在实践中,ajax不应该如何工作。如果我在加载页面后查看源代码,所有看起来都很好,并且对于每一行,都会创建一个唯一的xmlhttprequest和ajax请求
当我运行var_dump($jsonArray)
时,我得到NULL
导致此行为的原因是什么?
我的javascript:
$("#button1").click( function() {
<?php foreach ($results as $key => $row): ?>
var currentdate = new Date();
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$.ajax({
url: "insertvolume.php",
type: "POST",
data: {myData: xmlhttp.responseText},
contentType: "application/json",
success: function(output) {
//alert(output);
}
});
}
};
xmlhttp.open("GET","http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20IN%20(%22<?php echo $row["symbol"]; ?>%22)&format=json&env=http://datatables.org/alltables.env",true);
//xmlhttp.open("GET","http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20IN%20(%22LLNW%22,%22AAPL%22)&format=json&env=http://datatables.org/alltables.env",true);
xmlhttp.send();
<?php endforeach; ?>
});
一块php:
$jsonString = $_POST['myData'];
$jsonarray = json_decode($jsonString[0]['query']);
var_dump($jsonArray);
div元素中xmlhttprequest的json数组:
<div id="output">{"query":{"count":1,"created":"2016-02-15T16:03:29Z","lang":"de-DE","results":{"quote":{"symbol":"ZN","Ask":"2.05","AverageDailyVolume":"42000"}}}}</div>
答案 0 :(得分:3)
$jsonString
变量中有一个json字符串,但不是数组。
解码该字符串后,您将收到stdClass
的对象
请看下面的代码:
// your json string (the same as in $_POST['mydata'])
$json_str = '{"query":{"count":1,"created":"2016-02-15T16:03:29Z","lang":"de-DE","results":{"quote":{"symbol":"ZN","Ask":"2.05","AverageDailyVolume":"42000"}}}}';
$obj = json_decode($json_str);
var_dump($obj->query->results);
// the output
object(stdClass)[15]
public 'quote' =>
object(stdClass)[16]
public 'symbol' => string 'ZN' (length=2)
public 'Ask' => string '2.05' (length=4)
public 'AverageDailyVolume' => string '42000' (length=5)
答案 1 :(得分:1)
除罗马的答案外:
// your json string (the same as in $_POST['mydata'])
$json_str = '{"query":{"count":1,"created":"2016-02-15T16:03:29Z","lang":"de-DE","results":{"quote":{"symbol":"ZN","Ask":"2.05","AverageDailyVolume":"42000"}}}}';
$results = json_decode($json_str);
$results = $results->query->results;
<?php foreach ($results as $key => $row):
echo $row->symbol;
endforeach; ?>
您必须使用$ row-&gt;符号,因为它是对象,而不是数组。