jquery - 当服务器返回500时,在XMLHttpRequest对象中清空responseText

时间:2010-10-14 14:54:20

标签: javascript exception soap jquery cors

我必须在不同域之间通过javascript进行SOAP调用。在服务器端,有一个允许的域,方法和标题列表,它们由过滤器包含在响应中。当响应代码为200时,它运行良好(即使在不同的域之间),但是当在服务器端抛出异常时,xhr对象的状态为0而不是500,而responseText为空。在同一个域上使用时,状态和responseText都可以。

相关代码如下:

function onError(xhr, status, thrownError) {
    alert(xhr.status);
    alert(xhr.responseText);   
}

$.ajax({
    type: "POST",
    url: SOAPClient.Proxy,
    dataType: "xml",
    processData: false,
    data: content,
    context: context,
    contentType : SOAPClient.ContentType + "; " + SOAPClient.CharSet,
    error: onError,
    success: onSuccess,
    complete: onComplete,
    beforeSend: function(req) {
        req.setRequestHeader("Method", "POST");
        req.setRequestHeader("Content-Length", SOAPClient.ContentLength);
        req.setRequestHeader("SOAPServer", SOAPClient.SOAPServer);
        req.setRequestHeader("SOAPAction", soapReq.Action);
    }
});

我正在使用jQuery-1.4.2。允许的头是“SOAPServer”,“SOAPAction”和“Method”。 我在FF 3.6.10和Google Chrome 7.0.517.36

中尝试过

1 个答案:

答案 0 :(得分:0)

当服务器使用HTTP代码回复301时,FF 3.6.8返回xhr.status === 0.修复需要更改$ .ajax的httpSuccess函数

为了解决这个问题,我更改了jQuery 1.4.2的httpSuccess

原:

httpSuccess: function( xhr ) {
    try {
        // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
        return !xhr.status && location.protocol === "file:" ||
            // Opera returns 0 when status is 304
            ( xhr.status >= 200 && xhr.status < 300 ) ||
            xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
    } catch(e) {}

    return false;
},

改性:

httpSuccess: function( xhr ) {
    try {
        // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
        return !xhr.status && location.protocol === "file:" ||
            // Opera returns 0 when status is 304
            ( xhr.status >= 200 && xhr.status < 300 ) ||
            xhr.status === 304 || xhr.status === 1223 ||
            ( xhr.status === 0 && xhr.statusText.toUpperCase() === 'OK');            
    } catch(e) {}

    return false;
},