2

我正在使用中央 ajax 函数将 ajax Post 请求发送到服务器。这是函数的代码:

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); }
            }
        });
    }

当我尝试运行我的应用程序时,它在 chrome 中运行良好,但在 firefox 中它会抛出 404。当接受或内容类型未设置为 JSON 时,我的 REST 服务助手返回 404 ......所以我认为 firefox 可能不会添加标头但是当我查看发送的请求时:

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

您可以看到设置了必要的标题。我仍然在 Firefox 中获得 404,但在 chrome 中没有。

有什么想法吗?

4

1 回答 1

4

尝试这个,

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); }
        }
    });
}

参考jQuery ajax 接受属性有什么意义?它真的有什么作用吗?

阅读http://api.jquery.com/jquery.ajax/

于 2013-05-27T06:55:33.073 回答