jQuery 将 AJAX 返回数据转换为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6257837/
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 20:36:51  来源:igfitidea点击:

Converting AJAX return data to JSON

jqueryajaxjsonuncaught-exception

提问by jslamka

I am trying to retrieve data in a JSON object (which I have validated is correctly formatted) and output the data into the firebug console. I validated the JSON using JSONLint (http://jsonlint.com/) and know the data is not returning in JSON object because when I log it, it is logging as text rather than an object. When I look at the ajax post, there is a JSON tab and it shows the object, I just cannot retrieve it for some reason.

我正在尝试检索 JSON 对象中的数据(我已验证其格式正确)并将数据输出到 firebug 控制台。我使用 JSONLint (http://jsonlint.com/) 验证了 JSON,并且知道数据没有在 JSON 对象中返回,因为当我记录它时,它记录为文本而不是对象。当我查看 ajax 帖子时,有一个 JSON 选项卡,它显示了对象,但由于某种原因我无法检索它。

My ajax call is

我的 ajax 调用是

    $.ajax({
        url:'/coords/base',
        data: { type: obj.type, id: obj.id },
        dataType:'text',
        type:'get',
        async:false,
        success: function(data) {
            console.log(data);
        }
    });

My return data looks like such:

我的返回数据如下所示:

    {   
        "1": {"name":"TEXT","coords":[        
            { "entry":3,"x":15,"y":15 }     
        ]}}

When I set the AJAX call to a variable and add .responseText; to the end of the call, I can retrieve the plaintext return of the AJAX call. I thought I could then just use $.serialize() or $.parseJSON() but then I get an error "uncaught exception: Syntax error, unrecognized expression."

当我将 AJAX 调用设置为变量并添加 .responseText 时;到调用结束时,我可以检索 AJAX 调用的纯文本返回。我以为我可以只使用 $.serialize() 或 $.parseJSON() 但后来我收到一个错误“未捕获的异常:语法错误,无法识别的表达式”。

The end goal would be to retrieve the content from this responseText and use the JSON object throughout my files. This call must be done synchronously because it loads in vital data.

最终目标是从这个 responseText 中检索内容并在我的整个文件中使用 JSON 对象。此调用必须同步完成,因为它加载了重要数据。

Any help would be greatly appreciated.

任何帮助将不胜感激。

采纳答案by Félix Saparelli

Explicitly instruct jQuery to treat the response as text:

明确指示 jQuery 将响应视为文本:

$.ajax({
  // ...
  dataType: "text",
  // ...
});

You will then be able to get the JSON string. However, if you plan to convert it to a JS value thereafter, let me stop you: jQuery can do that for you automatically. If you specify the dataTypeto "json", or just let jQuery make an intelligent guess, the dataargument passed to the success:function will be the parsed JSON object.

然后您将能够获得 JSON 字符串。但是,如果您打算此后将其转换为 JS 值,让我阻止您:jQuery 可以自动为您完成。如果您指定dataTypeto "json",或者只是让 jQuery 进行智能猜测,则data传递给success:函数的参数将是解析后的 JSON 对象。

回答by matchew

why not use $.getJson()

为什么不使用$.getJson()

which is equivilant to

这相当于

 $.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

which you should then be able to do the following:

然后您应该能够执行以下操作:

$.getJSON('file.json', function(data) {
$.each(data, function(i) {
       console.log(data[i]);
     });
    });

edit

编辑

perhaps, I am misunderstanding the problem.

也许,我误解了这个问题。

EDIT #2Perhaps this question would help: Is there a version of $getJSON that doesn't use a call back?

编辑#2也许这个问题会有所帮助: 是否有不使用回调的 $getJSON 版本?

which suggests using this:

这建议使用这个:

$.ajax({
    type: 'GET',
    url: 'whatever',
    dataType: 'json',
    success: function(data) { console.log(data);},
    data: {},
    async: false
});

which of course, looks like what you have, so I feel I need to step back and reanalyze the problem.

当然,这看起来像你所拥有的,所以我觉得我需要退后一步重新分析问题。