使用jQuery解析JSON数据

时间:2017-04-06 07:15:33

标签: jquery json cordova

我有一个返回此JSON的Web服务:

[{
    "user_id": "1",
    "user_name": "User1",
    "user_age": "20"
}, {
    "user_id": "2",
    "user_name": "User2",
    "user_age": "21"
}, {
    "user_id": "3",
    "user_name": "User3",
    "user_age": "24"
}, {
    "user_id": "4",
    "user_name": "User4",
    "user_age": "34"
}, {
    "user_id": "5",
    "user_name": "User5",
    "user_age": "27"
}]

我想要的是我想将其填充到某个列表中,并且还希望点击index of list item以便我可以根据该索引值(user_id)检索更多信息。

我做的是:

function fetchFunction() {
    //fn.load('fetchPage.html');
    console.log("fetchFunction is invoked");

    var header = "<ons-list-header>My Inset ListTTT</ons-list-header>";

    $.ajax({
        type: 'POST',
        url: "fetchJSON.php",
        timeout: 5000,
        //dataType:'text',
        dataType:'json',
        success: function(data) {
             var data2 = JSON.stringify(data); //to string
             //var data2 = JSON.parse(data); //to string
             console.log("Index of list is: " + data2[0].user_id + " and username is: " + data2.user_name);         

             //alert("Index is: " + data[0]); 
             //$("#myListElement").html(header);
             //$("#myListElement").append(data);

             // Parse 'data' here
            console.log("SuccessED");
        },
        error: function(err) {
            ons.notification.alert("Error: " + err.status + ", " + err.statusText);
            console.log("Error: " + err);
            // console.log(err.status);
            // console.log(err.statusText);
            // $("#div1").text(err.responseText);
        }
    });
}

data2[0].user_id无所事事,只返回undefined

我在名为click的{​​{1}}上有一个div函数,因此我想显示点击功能触发的myListElement

user_id

如果你给我一些想法,我会很高兴。

BTW我正在使用: Cordova + OnSenUI 。 :/

谢谢。

PS:我将此if (event.target = "fetchPage2.html") { $("#myListElement").click(function(){ alert("List Item Clicked!"); }); } 作为列表。并希望在这里填充它。

ons-list

5 个答案:

答案 0 :(得分:2)

如果您的服务使用application/json返回数据,则使用直接数据变量

console.log("Index of list is: " + data[0].user_id + " and username is: " + data[0].user_name);   

测试代码

&#13;
&#13;
var data = [{
    "user_id": "1",
    "user_name": "User1",
    "user_age": "20"
}, {
    "user_id": "2",
    "user_name": "User2",
    "user_age": "21"
}, {
    "user_id": "3",
    "user_name": "User3",
    "user_age": "24"
}, {
    "user_id": "4",
    "user_name": "User4",
    "user_age": "34"
}, {
    "user_id": "5",
    "user_name": "User5",
    "user_age": "27"
}]

console.log("Index of list is: " + data[0].user_id + " and username is: " + data[0].user_name);
&#13;
&#13;
&#13;

如果您的服务返回带有文本的数据,则使用JSON.parse()函数

将转换数据转换为Json
var data2 = JSON.parse(data);
console.log("Index of list is: " + data2[0].user_id + " and username is: " + data2[0].user_name);  

测试代码

&#13;
&#13;
var data = '[{ "user_id": "1", "user_name": "User1", "user_age": "20" }, { "user_id": "2", "user_name": "User2", "user_age": "21" }, { "user_id": "3", "user_name": "User3", "user_age": "24" }, { "user_id": "4", "user_name": "User4", "user_age": "34" }, {"user_id": "5","user_name": "User5", "user_age": "27" }]'
var data2 = JSON.parse(data);
console.log("Index of list is: " + data2[0].user_id + " and username is: " + data2[0].user_name);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

通过这一小改动,您的代码可以正常运行:

var data2 = JSON.stringify(data);
data2 = $.parseJSON(data2);
console.log("Index of list is: " + data2[0].user_id + " and username is: " + data2[0].user_name);      

输出:Index of list is: 1 and username is: User1

演示:http://codepen.io/8odoros/pen/GWLmwB

答案 2 :(得分:1)

使用命令JSON.stringify()后,它不再是您可以访问的数组。如果您从服务器获取JSON对象,则可以直接访问data[someindex].user_id之类的对象。

如果您在这种情况下将数据作为字符串获取,则可以使用data = JSON.parse(data) 这是JSFIddle样本

要获取用户点击用户的详细信息:

var data = [{
    "user_id": "1",
    "user_name": "User1",
    "user_age": "20"
}, {
    "user_id": "2",
    "user_name": "User2",
    "user_age": "21"
}, {
    "user_id": "3",
    "user_name": "User3",
    "user_age": "24"
}, {
    "user_id": "4",
    "user_name": "User4",
    "user_age": "34"
}, {
    "user_id": "5",
    "user_name": "User5",
    "user_age": "27"
}]
success(data);
function success(data) {
    console.log("Index of list is: " + data[0].user_id + " and username is: " + data[0].user_name);
    for(var i=0;i<data.length;i++) {
        $("#myListElement").append('<ons-list-item>' + data[i].user_name + '</ons-list-item>');

    }
}

$("#myListElement").on('click', 'ons-list-item', function() {
var index = $(this).index();
	console.log('selected user details: name:  ' + data[index].user_name + '  id: ' + data[index].user_id + '  age : ' + data[index].user_age);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ons-list modifier="inset" id="myListElement">

</ons-list> 

以下是JSfiddle链接。

答案 3 :(得分:1)

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
    var myJSON = [{     "user_id": "1",     "user_name": "User1",     "user_age": "20" }, {     "user_id": "2",     "user_name": "User2",     "user_age": "21"              }, {     "user_id": "3",     "user_name": "User3",     "user_age": "24" }, {     "user_id": "4",     "user_name": "User4",     "user_age":              "34" }, {     "user_id": "5",     "user_name": "User5",     "user_age": "27" }];
    function fetchFunction(){
        $('#myListElement tbody').empty();
        $.each(myJSON,function(ind,obj){
            var htmlTemplate = "<tr userID=" + obj.user_id + " onClick='displayUserData(this)'><td></td><td>" + obj.user_id + "</td><td>"+ obj.user_name +"</td><td>"+ obj.user_age +"</td></tr>"
            $('#myListElement').append(htmlTemplate);
        });
    }
    function displayUserData(ref){
        myTr = ref;
        alert("User ID :: "+ $(ref).attr('userID') +" Row is Click");
    }
</script>
<input type="button" onClick="fetchFunction()" value="Fetch Data">
<table id="myListElement" border="1" cellspacing="0" cellpadding="10">
    <thead>
        <th>My Inset listdc</th>
        <th>Item A</th>
        <th>Item B</th>
        <th>Item C</th>
    </thead>
    <tbody>

    </tbody>
</table>

答案 4 :(得分:0)

您可以使用$ .parseJSON()函数解析json。请查看以下示例:

$( document ).ready(function() {
        var data = '[{"user_id": "1","user_name": "User1","user_age": "20"}, {"user_id": "2","user_name": "User2","user_age": "21"}, {"user_id": "3","user_name": "User3","user_age": "24"}, {"user_id": "4","user_name": "User4","user_age": "34"}, {"user_id": "5","user_name": "User5","user_age": "27"}]';  
        var data2 = $.parseJSON(data);
                console.log("Print json data");
                  $.each(data2, function(i, item) {
                        console.log("Index of list is: " + item.user_id + " and username is: " + item.user_name + " and age is: " + item.user_age);      
                  });                        
                console.log("End print");
        });