从Javascript / jQuery访问PHP中的数组

我将所有html,php和javascript / jquery代码放在一个文件中。 我在php(json_encode($ arr))中有一个数组$ 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 = ''; 

第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 $ .ajax()应该返回一个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