ajax upload cannot process JSON response or gives download popup
I'm using the AJAX plugin from Andris Valums:
- AJAX Upload ( http://valums.com/ajax-upload/ )
- Copyright (c) Andris Valums
It works great, except for the fact that I cannot send proper JSON as a response. I'm setting the headers to 'Content-Type', 'application/json' before sending the JSON-encoded response, and开发者_如何学Go in the plugin I'm saying that I'm expecting JSON:
responseType: "json",
This gives me a download popup asking to download the JSON/REPONSE file. The strange thing is, when I don't ass the correct "Content-Type" to my response, it works.
Of course I want to pass the correct response type, because all my jQuery 1.4 calls are depending on correct JSON.
Does anyone else have had this same problem or is there anyone out there willing to try this out ?
I'd love to use this plugin but only when I can return proper JSON with the correct content-type
You don't have to specify the application/json as the response Content-Type.
You can use Content-Type:text/plain an use the eval( '(' + response ')') function to evaluate your response and assign it to a JavaScript variable.
The example given by Damon explains it in more detail.
Other things you might want to check:
- Make sure your headers are sent BEFORE any output is sent
- Make sure your response is a valid JSON encoded string
Plugin creates invisible file input on top of the button you provide, so when user clicks on your button the normal file selection window is shown. And after user selects a file, plugin submits form that contains file input to an iframe. So it isn’t true ajax upload, but brings same user experience.
Since the plugin is not true Ajax and because your setting the content type to application/json, the only response you will get will be a file download dialog.
The only way (i can see) would be to remove the content type you have set and within javascript use something like
var jsonObj = eval('(' + response + ')');
I used the above method a couple of days ago using the same plugin.
I'm having the same problem, and I don't think sending it any other method besides json is helping...
I think it has to do with the method by which the iframe content is interpreted into a response string before it is being eval()'ed into a JSON object.
it appears that if the json_encode()'ed string returned by the server contains HTML with quotation marks backwhacked (\"), the string ajaxupload uses becomes escaped in some manner before the eval, breaking the JSON object.
I can't see a way to fix it yet, though :(
精彩评论