Reputation: 2492
I am working with .load
function in jQuery to load a html page into a div with ajax but I have problem since server always doesn't send a html, sometimes it send a json
and I want to get that json
with .load
.
I thought it would be a response
in callback function in .load
but it return undefined and just put that json
into the div so how can I get that json
with .load
.
The server send this json :
{ok : false}
Here is my jQuery code:
$( "#div").load( "url", function( response, status, xhr ) {
////how can I get the false result here response.ok return nothing!!!
console.log(response.ok);
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#div" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
Upvotes: 4
Views: 8990
Reputation: 633
Using response to replace #div html content :
$("#div").load("url", function (responseTxt, statusTxt, xhr) {
if (statusTxt == "success") {
var responseAsObject = $.parseJSON(response);
$(this).html( responseAsObject.response );
}
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
Upvotes: 2
Reputation: 2819
i think you have to do something like this:
$("#div").load( "url", function( response, status, xhr ) {
var responseAsObject = $.parseJSON(response);
console.log(responseAsObject.ok);
});
Upvotes: 4