JQuery's Ajax function works in chrome but returns 404 in firefox

匿名 (未验证) 提交于 2019-12-03 09:58:14

问题:

I'm using a central ajax function to send ajax Post requests to a server. This is the code of the function:

function postJson(url, jsObj, whenSuccess, whenError){         $.ajax({             type: "post",             headers: {                 "Accept": "application/json, text/javascript, */*; q=0.01",                 "Content-Type": "application/json, text/javascript, */*; q=0.01"             },             dataType: "json",             url: url,             data: JSON.stringify(jsObj),             success: function(result){                 if(whenSuccess !== undefined){ whenSuccess(result); }             },             error: function(xhr){                 if(whenError !== undefined){ whenError(xhr.status); }             }         });     }

When I try to run my application it works fine in chrome, but in firefox it throws a 404. My REST service helper returns a 404 when the accept or content type isn't set to JSON... so I thought that firefox might not add the headers but when I look at the sent request:

Request URL: http://localhost:9081/api/1/localize/validation.json  Request Method: POST  Status Code: HTTP/1.1 404 Not Found  Request Headers 08:40:10.000  X-Requested-With:XMLHttpRequestUser-Agent...... Referer:http://localhost:9081/kportal/ Pragma:no-cacheHost:localhost:9081 Content-Type:application/json, text/javascript; charset=UTF-8, */*; q=0.01 Content-Length:2 Connection:keep-alive Cache-Control:no-cache Accept-Language:en-US,en;q=0.5 Accept-Encoding:gzip, deflate Accept:application/json, text/javascript, */*; q=0.01

You can see that the necessary headers are set. Still I'm getting a 404 in firefox but not in chrome.

Any thoughts?

回答1:

Try this,

function postJson(url, jsObj, whenSuccess, whenError){     $.ajax({         type: "post",         contentType: "application/json; charset=utf-8",         accepts: {             xml: 'text/xml',             text: 'text/plain'         },         dataType: "json",         url: url,         data: JSON.stringify(jsObj),         success: function(result){             if(whenSuccess !== undefined){ whenSuccess(result); }         },         error: function(xhr){             if(whenError !== undefined){ whenError(xhr.status); }         }     }); }

Refer What is the point of jQuery ajax accepts attrib? Does it actually do anything?

Read http://api.jquery.com/jquery.ajax/



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!