我有一个单一的文件中的所有我的HTML,PHP和JavaScript / jQuery代码。 我在PHP阵列$ ARR(json_encode($ ARR)),其在打印时显示了在PHP的数据。 如何访问它的JavaScript。 该阵列包含所有来自查询执行的结果集的行。 我已经看过了jsonParse和VAR json_obj =,但没有得到任何结果。 我是新手,所以任何帮助表示赞赏。 到目前为止我的代码在PHP:
$result_again = $conn->query($sql_again);
if ($result_again->num_rows > 0)
{
$resultarray = array();
while($row_again = $result_again->fetch_assoc())
{
$resultarray[] = $row_again;
}
}
echo json_encode($resultarray);
我在.js文件的代码:
$( document ).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "secondform.php",
success: function(data) {
alert("Result: " + data);
}
});
});
第1步:
渲染json_encode($ ARR)到JavaScript字符串变量。
var json = '<?= json_encode($arr) ?>';
第2步:
解析JSON字符串成JavaScript对象。
var obj = JSON.parse(json);
或者,如果你正在使用jQuery:
var obj = jQuery.parseJSON(json);
现在,您有一个JavaScript对象,您可以访问像下面的性质:)
alert(obj.title); // show object title
alert(obj[0].id); // grab first row of array and show 'id' column
编辑 - 在回答slugspeeds更新
好了,看起来像你这样做是使用jQuery的AJAX方法。 因为你的PHP脚本使用json_encode()jQuery的$。阿贾克斯()应该返回一个JavaScript数组对象。
$( document ).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "secondform.php",
success: function(arr) {
console.log(arr); // show array in console (to view right-click inspect element somewhere on screen, then click console tab)
$.each(arr, function( index, row ) { // loop through our array with jQuery
console.log('array row #'+index, row); // show the array row we are up to
// you can do what you want with 'row' here
});
}
});
});
供参考: https://developer.chrome.com/devtools/docs/console