How to make sense out of an object returned in jQuery
I have this jQuery code:
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
// ? :)
alert (dataString);
},
error : function(data)
{
alert("ajax error, json: " + data);
//for (var i = 0, l = json.length; i < l; ++i)
//{
// alert (json[i]);
开发者_JS百科 //}
}
});
And when I use it, I get in the alert something cryptic like this: object XMLHTTPReqest
How do I actually get the value that was passed in from the AJAX?
Thanks!
In a couple ways:
console.log(data); // allows you to view your object in a tree in the console
or
alert(JSON.stringify(data)); // alerts a serialized string of the object
or in chrome/safari and firefox (firebug) set a break point and check it out.
have you tried using the Firefox plugin called FireBug? That's the first place I start as it will show you the exact structure, and data, of the json object returned.
from there it's a simple matter of coding in the object names etc.
Firefox - Download Firebug. A must for any web dev.
Chome: instead of alert, do "console.log(data);" This should spit out the object and you can view its properties in the console (hit F12 for that).
Alternatively, write "debugger;" right before your alert and the browser will pause execution. You need to have Firebug running or Chrome Dev Tools open.
I assume you're talking about the error handler.
The signature for the jQuery AJAX error handler is
error(jqXHR, textStatus, errorThrown)
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred
You cannot get the "data" returned as there is no data, just an error.
First, you're alerting dataString
, not anything returned from the server, at least in the success
callback. .ajax()
callback signatures look like this: success(data, textStatus, jqXHR)
, so if you're getting real data back, it can be accessed like any JSON object, via the data
parameter. In error
it's error(jqXHR, textStatus, errorThrown)
, so if that's what you're talking about, it kind of makes sense.
Use Firebug/Chrome/proxy/etc. to make sure what you're getting back from the server is what you expect, or just log it to the console.
精彩评论