简体   繁体   English

JSON编码数组,如何在jQuery中使用

[英]JSON encoded array, how to use in jQuery

Ok I've got this code in a file test.php: 好的,我在文件test.php中得到了以下代码:

<?php
$con = mysqli_connect("localhost", "user", "password", "DB");
if (mysqli_connect_errno()){
    echo "failed to connect:" . mysqli_connect_error();
}

$grab = mysqli_query($con, "SELECT * FROM DB");
$cars = array();
while($row = mysqli_fetch_assoc($grab)){
    array_push($cars, array("id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"];
}
echo json.encode($cars);

And I've got the jQuery code on my HTML page: 我的HTML页面上有jQuery代码:

$.get("test.php", function($cars){
    $("itemNameLink1").html($cars.name);
    console.log($cars.name);
});

My next question is how do I access the data in my json_encoded array and use it in my jQuery on the HTML page. 我的下一个问题是如何访问json_encoded数组中的数据并在HTML页面上的jQuery中使用它。 Right now I only get back undefined in console log. 现在,我只能在控制台日志中返回undefined。 It was only my first try so wasn't disheartened by it. 这只是我的第一次尝试,因此并没有因此而灰心。 But any advise would be appreciated. 但任何建议将不胜感激。

That's because you try to access name property of $cars array instead of name property of each car. 这是因为您尝试访问name的属性$cars数组,而不是name每台车的性能。 You should to iterate through your array first: 您应该首先遍历数组:

for(var car in $cars){
    console.log(car.name);
} 

or 要么

$cars.forEach(function(e){
    console.log(e);
});

if you maintain only modern browsers. 如果您仅维护现代浏览器。 Or use $.each method as @StartCoding mentioned. 或使用$.each方法,如@StartCoding所述。

AND , again as @StartCoding mentioned use $.getJSON instead of $.get or $.parseJSON($cars) if you've got a string in you response (it possible if your server returned wrong MIME-type [ text/plain for example instead application/json ]). AND ,正如@StartCoding所述,如果响应中包含字符串,则使用$.getJSON代替$.get$.parseJSON($cars) (如果服务器返回错误的MIME类型[ text / plain而不是示例application / json ])。

$.get("test.php", function($cars){
 $.each($.parseJSON($cars), function(i, val){
$("itemNameLink1").html(val.name);
console.log(val.name);
});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM