如何解析JSON数组?

时间:2012-10-30 09:22:28

标签: php jquery json

两者可以分为单独的数组格式化的PHP脚本返回的JSON字符串吗? 我的JS代码

function GetData(id){
    $.ajax({
        url: 'list.php',
        data: 'id=' + id,
        type: 'POST',
        success: function(data){
            alert(data)
            console.log(data)
        }
    })
}

我的list.php

<?php
$id = $_POST['id'];
$connect = mysql_connect("localhost", "admin", "118326") or die(mysql_errno());
$db = mysql_select_db("flabers", $connect) or die(mysql_error());
$result = mysql_query("SELECT * FROM list WHERE id = '$id'") or die(mysql_error());
$array = mysql_fetch_assoc($result) or die(mysql_errno());
echo json_encode($array);
?>

返回json字符串

{"id":"88","country":"Korea, Japan, USA","brand":"Samsung, Sony, HTC"} 

如何获得两个阵列的国家和品牌?

3 个答案:

答案 0 :(得分:1)

用户dataType:'json'

 $.ajax({
    url: 'list.php',
    data: 'id=' + id,
    contentType: 'application/json',
    type: 'POST',
    dataType: 'json',
    success: function(data){
        alert(data)
        console.log(data) //access it like data.id, data.country etc
    }
})

答案 1 :(得分:0)

PHP应该通知客户端它正在发送JSON而不是HTML(默认情况下它会发送)。

header('Content-Type: application/json');
然后,jQuery会自动将其解析为JavaScript对象。

答案 2 :(得分:-1)

以下面的方式解析json。

//var obj = JSON.parse(jsonstring); //javascript way

var obj = jQuery.parseJSON(jsonstring); //jquery way

alert(obj.country + " : " + obj.brand);