jQuery parseJSON object question/issue
I've been playing around with jQuery's parseJSON and simplejson and I can't seem to figure out why I'm unable to get my variables to print or compare.
I know my Python return statement is correct, because if it wasn't the jQuery.ajax would return false and the "error" code would run. So I'm not sure what I'm doing wrong with the jQuery
Here's the code I'm trying to use:
Pythong/Django return statem开发者_JAVA百科ent...
return HttpResponse(json.dumps({'result': True}), mimetype='application/json')
jQuery/javascript... (.ajax function... i just left in the good parts)
success: function(data, textStatus, jqXHR) {
jQuery(".signup").attr('disabled', false);
//parse return data
var obj = jQuery.parseJSON(data);
if(obj.result == true){
//$('.signup-area .heading').hide();
//$('#signup').hide();
$('.success').show().append(obj.result);
}
else{
$('.signup-area .heading').hide();
$('#signup').hide();
$('.success').show().append('in the else');
}
},
error: function(jqXHR, textStatus, errorThrown) {
jQuery(".signup").attr('disabled', false);
$('.fail').show().append(errorThrown);
}
As far as I know, the jQuery ajax function takes is 'dataType' parameter which you can specify 'json' so that jQuery will automatically parse the data. In that case you dont have to call parseJson in order to get response as json.
Something like
jQuery.ajax({
url:url,
dataType:'json',
success:function(data){
//data will be in json format so no need to parse it again.
},
error:function(){}
});
I hope this helps.
I had this problem recently and it was because I was using single quotes in my JSON, which parseJSON considers invalid.
$.parseJSON("{'key':'value'}")
Invalid JSON: {'key':'value'}
$.parseJSON('{"key":"value"}')
Object
The way I figured this out was to call parseJSON from the JS console window in chrome. I then verified this was the issue by running my JSON through JSONLint
精彩评论