从 JQuery.ajax 成功数据解析 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5289078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:54:30  来源:igfitidea点击:

Parse JSON from JQuery.ajax success data

jsonjquery

提问by actkatiemacias

I am having trouble getting the contents of JSON object from a JQery.ajax call. My call:

我无法从 JQery.ajax 调用中获取 JSON 对象的内容。我的电话:

$('#Search').click(function () {
    var query = $('#query').valueOf();
    $.ajax({
        url: '/Products/Search',
        type: "POST",
        data: query,
        dataType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data);
            for (var x = 0; x < data.length; x++) {
                content = data[x].Id;
                content += "<br>";
                content += data[x].Name;
                content += "<br>";
                $(content).appendTo("#ProductList");
               // updateListing(data[x]);
            }
        }
    });
});

It seems that the JSON object is being returned correctly because "alert(data)" displays the following

似乎正确返回了 JSON 对象,因为“警报(数据)”显示以下内容

[{"Id": "1", "Name": "Shirt"}, {"Id": "2", "Name":"Pants"}]

but when I try displaying the Id or Name to the page using:

但是当我尝试使用以下方法在页面上显示 Id 或 Name 时:

content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";

it returns "undefined" to the page. What am I doing wrong?

它将“未定义”返回到页面。我究竟做错了什么?

Thanks for the help.

谢谢您的帮助。

回答by Marcelo Cantos

The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataTypeto just 'json'to have it converted automatically.

数据以 JSON 的字符串表示形式返回,您不会将其转换回 JavaScript 对象。将 设置dataType为 just'json'使其自动转换。

回答by abobreshov

I recommend you use:

我建议你使用:

var returnedData = JSON.parse(response);

to convert the JSON string (if it is just text) to a JavaScript object.

将 JSON 字符串(如果它只是文本)转换为 JavaScript 对象。

回答by aash

One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do

您可以确保不会发生这种类型的错误(使用字符串而不是 json)的方法之一是查看alert. 当你做

alert(data)

if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert

如果 data 是一个字符串,它将打印包含的所有内容。但是,如果您打印的是 json 对象。您将在警报中收到以下响应

[object Object]

If this the response then you can be sure that you can use this as an object (json in this case).

如果这是响应,那么您可以确定可以将其用作对象(在这种情况下为 json)。

Thus, you need to convert your string into json first, before using it by doing this:

因此,您需要先将字符串转换为 json,然后再使用它:

JSON.parse(data)

回答by Amin Saadati

It works fine, Ex :

它工作正常,例如:

$.ajax({
    url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "?????",
    type: 'GET',
    cache: false,
    success: function(result) {
        //  alert(jQuery.dataType);
        if (result) {
            //  var dd = JSON.parse(result);
            alert(result[0].Id)
        }

    },
    error: function() {
        alert("No");
    }
});

Finally, you need to use this statement ...

最后,你需要使用这个语句......

result[0].Whatever

回答by Steve

Well... you are about 3/4 of the way there... you already have your JSON as text.

嗯......你大约是那里的 3/4......你已经有你的 JSON 作为文本。

The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.

问题是您似乎正在处理这个字符串,就好像它已经是一个 JavaScript 对象,它具有与传输的字段相关的属性。

It isn't... its just a string.

它不是……它只是一个字符串。

Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.

像“content = data[x].Id;”这样的查询 肯定会失败,因为 JavaScript 没有找到附加到它正在查看的字符串的这些属性......同样,它只是一个字符串。

You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.

您应该能够通过... 是的... JSON 对象的 parse 方法简单地将数据解析为 JSON。

myResult = JSON.parse(request.responseText);

Now myResult is a javascript object containing the properties that were transmitted through AJAX.

现在 myResult 是一个 javascript 对象,其中包含通过 AJAX 传输的属性。

That should allow you to handle it the way you appear to be trying to.

这应该允许您以您似乎尝试的方式处理它。

Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQueryor JSON2.

看起来 JSON.parse 是在添加 ECMA5 时添加的,所以任何相当现代的东西都应该能够在本机处理这个……如果你必须处理化石,你也可以尝试使用外部库来处理这个问题,例如jQueryJSON2

For the record, this was already answered by Andy E for someone else HERE.

作为记录,这已经由安迪 E 在这里为其他人回答了。

edit- Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.

编辑- 看到了对“官方或可靠来源”的请求,我认为最可信的编码员之一可能是 John Resig ~ ECMA5 JSON~ 我会链接到有关本机 JSON 支持的实际 ECMA5 规范,但我会而是将某人推荐给像 Resig 这样的大师,而不是枯燥的规范。

回答by arabeske

Try the jquery eachfunction to walk through your json object:

尝试使用 jqueryeach函数遍历您的 json 对象:

$.each(data,function(i,j){
    content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
    $('#ProductList').append(content);
});

回答by Suchit kumar

you can use the jQuery parseJSON method:

您可以使用 jQuery parseJSON 方法:

var Data = $.parseJSON(response);

回答by krunal shimpi

input type Button

输入类型按钮

<input type="button" Id="update" value="Update">

I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below

我已经成功地在 perl 中发布了一个带有 AJAX 的表单。发布表单后,控制器返回如下 JSON 响应

$(function() {

    $('#Search').click(function() {
        var query = $('#query').val();
        var update = $('#update').val();

        $.ajax({
            type: 'POST',
            url: '/Products/Search/',
            data: {
                'insert': update,
                'query': address,
            },
            success: function(res) {
                $('#ProductList').empty('');
                console.log(res);
                json = JSON.parse(res);
                for (var i in json) {
                    var row = $('<tr>');
                    row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
                    row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
                    $('</tr>');
                    $('#ProductList').append(row);
                }
            },
            error: function() {
                alert("did not work");
                location.reload(true);
            }
        });
    });
});

回答by krunal shimpi

parse and convert it to js object that's it.

解析并将其转换为 js 对象就是这样。

success: function(response) {
    var content = "";
    var jsondata = JSON.parse(response);
    for (var x = 0; x < jsonData.length; x++) {
        content += jsondata[x].Id;
        content += "<br>";
        content += jsondata[x].Name;
        content += "<br>";
    }
    $("#ProductList").append(content);
}

回答by Sky Yip

From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON()based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).

Or you can set the dataTypeto jsonto convert it automatically.

来自 jQuery API:设置为dataType, 如果没有指定,jQuery 将尝试$.parseJSON()根据响应的 MIME 类型(JSON 文本的 MIME 类型是“application/json”)推断它(在 1.4 JSON 中将产生一个 JavaScript 对象)。

或者你也可以设置dataTypejson它自动转换。