AJAX返回的数据转换成JSON [英] Converting AJAX return data to JSON

查看:744
本文介绍了AJAX返回的数据转换成JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检索一个JSON对象的数据(我已经验证是正确的格式)和输出数据到萤火虫控制台。我验证使用JSONLint的JSON(http://jsonlint.com/),并知道数据没有返回的JSON对象,因为当我登录,它被记录为文本,而不是一个对象。当我看阿贾克斯后,有一个JSON标签,它显示了对象,我只是不能检索它的某些原因。

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.

我的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 }     
        ]}}

当我设置了AJAX调用给一个变量,并添加.responseText;到呼叫的结束,我可以检索AJAX调用的明文返回。我当时认为我可以只使用$ .serialize()或$ .parseJSON(),但后来我得到一个错误未捕获的异常:语法错误,无法识别的EX pression

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."

最终目标是检索该responseText的内容,并使用JSON对象在我的文件。此调用必须做到同步,因为它加载的重要数据。

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.

任何帮助将是很大的AP preciated。

Any help would be greatly appreciated.

推荐答案

明确指示的jQuery对待响应为文本:

Explicitly instruct jQuery to treat the response as text:

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

您将能够获得JSON字符串。不过,如果你计划将其随后转换为JS值,让我阻止你:jQuery的可以自动为你做的。如果指定了的dataType JSON,或只是让jQuery的做出明智的猜测,在数据传递给成功的说法:函数将被解析的JSON对象

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 dataType to "json", or just let jQuery make an intelligent guess, the data argument passed to the success: function will be the parsed JSON object.

这篇关于AJAX返回的数据转换成JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆