Why is alert not run even though $.getJSON runs fine? (Callback not executed, even though the request works fine with getJSON)
I have a snippet of code such as:
$.getJSON("http://mysite.org/polls/saveLanguageTest?url=" + escape(window.location.href) + "&callback=?",
function (data) {
var serverResponse = data.result;
console.log(serverResponse);
alert(serverResponse);
});
It works fine in the sense that it makes a cross-domain request to my server and the server saves the data as I expect. Unfortunately, even though the server saves data and sends back a response I just can't get any alert or the console.log run. Why may be that? The server side code is (if that is relevant):
def saveLanguageTest(request):
callback = request.GET.get('callback', '')
person = Person(firstName = 'Anonymous',
ipAddress = request.META['REMOTE_ADDR'])
person.save()
webPage = WebPage(url = request.GET.get('url'))
webPage.save()
langTest = LanguageTest(type = 'prepositionTest')
langTest.person = person
langTest.webPage = webPage
langTest.save()
req ['result'] = 'Your test is saved.'
response = json.dumps(req)
response = callback + '(' + response + ');'
return HttpResponse(response, mimetype = "application/json")
What am I missing? (I tried the same code both within my web pages and inside the Firebug and I al开发者_JAVA百科ways have the problem stated above.)
$.getJSON
likes to fail silently when it received malformed JSON. Check that your JSON is well-formed, or try with a simple tiny bit of JSON to get it working. From the manual:
Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.
Are you sure that your Django code is returning, and not raising an exception? As far as I can see, you have invalid code there - you reference req['result']
without first defining req
.
As suggested in the comments, look at Firebug's Console tab to see what is actually being returned from your call. You may find it's actually a Django error page.
My bad' I've forgotten to add
req = {}
before
req ['result'] = 'Your test is saved.'
(And another failure on my side was to implement an error handling function for the callback, if that's possible at all for jQuery's default JSONP functionality).
精彩评论