开发者

jQuery cannot understand JSON response when Content-Type is not set to "application/json"

开发者 https://www.devze.com 2023-02-08 10:28 出处:网络
The Google App Engine server is returning a JSON String in response to a POST: self.response.headers.add_header(\"Content-Type\", \"application/json\")

The Google App Engine server is returning a JSON String in response to a POST:

self.response.headers.add_header("Content-Type", "application/json")       
return self.response.out.write(json_string)

This works on my local development server running in the Google App Engine Launcher. The header is being set, and the jQuery code is parsing the response correctly.

However, in pr开发者_如何学Gooduction, on the Google Frontend (when I deploy to production), the page is breaking because jQuery is not parsing the response correctly. The ONLY difference I can find between local and production (they are running the same code) is that the response on production, is ignoring my attempt to set the Content-Type to "application/json".

So that probably means I'm trying to set an illegal/non-standard Content-Type. BUT, it works locally, and that is how I got my jQuery to understand the JSON String.

So, how do I format the response so that jQuery will know it's JSON and parse correctly?


Just pass in "json" as the dataType argument to the AJAX call, and presto, the response will be treated as json no matter the content-type :)


Try with:

self.response.headers['Content-Type'] = "application/json"
self.response.out.write(json_string)


This may seem silly, but maybe you need to capitalize the first parameter to add_header, so it will be "Content-Type"? It might be that your local server is forgiving about the parameters, while the Google servers will just submit the header as-is. Can you check the headers that are being returned via Firebug or WebKit developer panel, to see what response headers are being sent?

0

精彩评论

暂无评论...
验证码 换一张
取 消