将 jQuery 和 JSON 与 AJAX responseText 一起使用?

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

Using jQuery and JSON with AJAX responseText?

jsonjqueryxmlhttprequest

提问by karim79

Ok, I'm a bit new when it comes to jQuery and json. If I'm using json as my return type, can I still retrieve responseText from an XMLHttpRequest object?

好的,我对 jQuery 和 json 有点陌生。如果我使用 json 作为返回类型,我还能从 XMLHttpRequest 对象中检索 responseText 吗?

here's the code that i'm using:

这是我正在使用的代码:

json response: {"clients": []}

$.ajax({
        type: "POST",
        url: "/myurl/whatever.php",
        data: myData,
        dataType: "json",

        success: function(msg){
            status.html(msg[0]);
        },
        error: function(msg) {
                status.html("Error: " + msg[0]);
        }

        });

is the use of msg[0] correct if i want to output the json response or am i missing something?

如果我想输出 json 响应或者我遗漏了什么,使用 msg[0] 是否正确?

how can i still use the above code with XMLHttpRequest to get the status, responseText, etc.

我怎样才能将上面的代码与 XMLHttpRequest 一起使用来获取状态、响应文本等。

thanks, all!

谢谢,所有!

回答by karim79

As far as I know, the call to $.ajax returns a XHR object, and from that the responseText can be extracted, e.g.:

据我所知,对 $.ajax 的调用返回一个 XHR 对象,并且可以从中提取 responseText,例如:

var xhr = $.ajax( {
                        url:' someInfo.php',
                        data: 'which=squirrels',
                        asynch: true
                } );

var resp = xhr.responseText;

The response text will contain a json string, which would need to be converted to an object to be of any use.

响应文本将包含一个 json 字符串,需要将其转换为一个对象才能使用。

If you want to use the response as a json object directly within your success: function, do as @cloudhead suggested, and use msg. The dataType : "json" in your optionstakes care of the conversion for you.

如果您想直接在您的success: 函数中使用响应作为 json 对象,请按照@cloudhead 的建议进行操作,并使用msg。数据类型:“JSON”在你的选择负责转换的为您服务。

回答by cloudhead

If you're using json, then you get a json object back, not an XML object. You can output it directly, without using [0].

如果您使用的是 json,那么您将返回一个 json 对象,而不是一个 XML 对象。可以直接输出,不用[0]。