【问题标题】:How to parse Json object in Jquery如何在 Jquery 中解析 Json 对象
【发布时间】:2017-09-03 20:33:45
【问题描述】:

我在 JSON 方面有一点经验我在我的 Android 应用程序上做了这件事,现在在我的网页中再次使用 JSON 作为 AJAX 响应,我研究了关于 ajax 并找到了一个使用 JSON 将我的数据获取到数据库中的教程,所以我尝试了,但我不知道如何解析对象。

我的 Jquery 代码。

$.ajax({
    type: 'GET',
    dataType: 'json',
    url: 'functions/json.php',
    success: function(response){
   var json = $.parseJSON(response);
   alert(json.firstname) //where my response is $response['firstname']
},
error: function(data){
   var json = $.parseJSON(data);
   alert(json.error);
}
});

使用 php 我将 jsonArray 回显为 json_encode 并继承 json 输出

{"id":"2","firstname":"john","lastname":"Doe"}

使用 google chrome 控制台出现此错误

Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)

当函数响应输出为alert(reponse) 输出是

[object Object]

【问题讨论】:

    标签: javascript php jquery json ajax


    【解决方案1】:

    不要解析它。你已经告诉 jQuery:

    dataType: "json"
    

    所以response解析 对象,而不是JSON。直接使用即可:

    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: 'functions/json.php',
        success: function(response){
            alert(response.firstname);
        },
        error: function(data) {
            // `data` will not be JSON
        }
    });
    

    还要注意error回调的第一个参数不会是JSON,也不是错误回调中解析JSON的结果。

    详情请见the documentation

    【讨论】:

    • 非常感谢您在 ajax 最佳答案中的新功能,但我会等到 12 分钟 :)
    • {"success":true,"message":[{"id":"2","firstname":"john","lastname":"doe"},[{"id ":"3","firstname":"jane","lastname":"doe"}]} 使用多个数组我将如何回显这个?
    • @RaizeTech:我只看到一个数组。要遍历该数组(即response.message),请使用this question's answers 中介绍的任何技术,例如response.message.forEach(function(entry) { alert(entry.firstname); });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2021-03-19
    • 1970-01-01
    • 2017-07-14
    • 2011-07-30
    • 2015-05-18
    相关资源
    最近更新 更多