使用jQuery和JSON与AJAX responseText?

时间:2022-09-15 11:44:54

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来获取状态,responseText等。

thanks, all!

2 个解决方案

#1


6  

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 options takes care of the conversion for you.

如果你想在你的success:function中直接使用响应作为json对象,请按@cloudhead建议,并使用msg。您选择的dataType:“json”负责为您进行转换。

#2


1  

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]。

#1


6  

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 options takes care of the conversion for you.

如果你想在你的success:function中直接使用响应作为json对象,请按@cloudhead建议,并使用msg。您选择的dataType:“json”负责为您进行转换。

#2


1  

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]。