Using jQuery and JSON with AJAX responseText?

Ok, I'm a little newbie when it comes to jQuery and json. If I use json as the return type, can I get a Text response from an XMLHttpRequest object?

here is the code i use:

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 using msg [0] correct if i want to output json answer or am i missing something?

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

Thank you all!

+4
source share
2 answers

As far as I know, calling $ .ajax returns an XHR object, and a responseText file can be extracted from it, for example:

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

The response text will contain a json string that must be converted to the object to be used.

If you want to use the response as a json object directly in your success function: do as @cloudhead suggested and use msg . DataType: "json" in options will take care of you for conversion.

+6
source

If you use json, then you are returning a json object, not an XML object. You can output it directly without using [0].

+1
source

Source: https://habr.com/ru/post/1286110/


All Articles