【问题标题】:How to respond with a status code 500 to an ajax jsonp request如何以状态码 500 响应 ajax jsonp 请求
【发布时间】:2016-06-04 00:38:47
【问题描述】:

我有一个向 C# HttpHandler 发出 ajax jsonp 请求的应用程序。

function RequestData() {
var parameters = 'value1=' + value + '&value2=' + value2;
$.ajax({
    type: "GET",
    url: 'https://localhost:44300/checkvalues?' + parameters,
    dataType: "jsonp",
    headers: { "cache-control": "no-cache" },
    success: function (msg) {
        alert('all good')
    },
    error: function (jqXHR, exception) {
        alert(jqXHR.status);
    }
});

这里是一些服务器端代码。

if (OK)
{
    response.ContentEncoding = System.Text.Encoding.UTF8;
    response.ContentType = "application/javascript";
    response.Write(callback + "({ data: 'allOK' });");
}
else
{
    //error
    response.StatusCode = 500;
    response.SuppressFormsAuthenticationRedirect = true;
    response.StatusDescription = "error";
    response.End();
}

当 OK 为真时,没有问题。 ajax 成功函数按预期调用。但是我将响应状态代码设置为例如的那一刻500 触发 ajax 请求的错误部分,从未收到服务器响应 - 没有任何反应。

如何修改我的响应代码以进入 ajax 错误部分?

我可以通过更改响应来触发解析错误,但我想使用 Http 状态代码来做到这一点。

【问题讨论】:

  • 为什么不在 JSON 中使用 send statusCode。
  • 在 webinspector (F12) 中查看请求。什么是响应状态码?我希望您的 error 函数能够触发。
  • @jcubic - 在我看来,我必须处理“成功”部分中的错误。如果可能的话,在错误部分处理它似乎更合乎逻辑。
  • 查看我链接的副本中提供的答案。跨域 jsonp 请求不会调用错误 ajax Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
  • 建议你实现CORS而不是jsonp

标签: javascript c# jquery ajax jsonp


【解决方案1】:

您可以检测到 JSONp 错误。我不确定为什么 jQuery 选择不这样做。

这是一个不使用 jQuery 的 JSONp 实现。您可能需要对其进行一些修改才能使其正常工作。例如,我不确定 jQuery 如何与 callback_name 通信。

function jsonp(success_callback, error_callback) {
    var script, callback_name;
    var parameters = 'value1=' + value + '&value2=' + value2;

    callback_name = "generate random name";

    function after() {
        setTimeout(function () {
            document.getElementsByTagName("head")[0].removeChild(script);
        }, 1);
    }

    script = document.createElement('script');
    window[callback_name] = function (response) {
        after();
        success_callback(response);
    };
    script.type = 'text/javascript';
    script.src = "https://localhost:44300/checkvalues?" + parameters + "&callback=" + callback_name;
    script.async = true;
    script.addEventListener('error', function () {
        after();
        error_callback();
    });
    document.getElementsByTagName("head")[0].appendChild(script);
}

jsonp(function () {
    alert("success");
}, function () {
    alert("failure");
});

【讨论】:

  • 标记为正确 - 它有效。但是,我将按照@ᾠῗᵲᄐᶌ 添加的重复链接之一中的建议使用 jQuery 插件:github.com/jaubourg/jquery-jsonp - 尽管我没有在该解决方案中找到 http 状态代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
  • 2023-04-06
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
相关资源
最近更新 更多