I have an application that fires an ajax jsonp request to a C# HttpHandler.
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);
}
});
And here is some of the server side code.
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();
}
When OK is true, there is no problem. The ajax success function is called as expected. But the minute that I set the response status code to eg 500 to trigger the error section of the ajax request, the server response is never received - nothing happens.
How can I modify my response code to enter the ajax error section?
I can trigger a parse-error by changing the response, but I want to do it with Http Status Codes.
You can detect a JSONp error. I'm not sure why jQuery chooses not to.
Here is a JSONp implementation that doesn't use jQuery. You might need to tinker with it a bit to make it work. For instance I'm not sure how jQuery communicates the 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");
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.