javascript 如何测试ajax错误回调?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12455853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test ajax error callback?
提问by blue-sky
Within an ajax request how can the error callback be tested ? Is it possible to simulate a network connection error ?
在 ajax 请求中如何测试错误回调?是否可以模拟网络连接错误?
$.ajax({
url: "myUrl",
type: 'post',
dataType : "json",
data : ({
myJson
}),
success : function(jsonSaveResponse) {
},
error: function (xhr) {
}
});
回答by Mild Fuzz
You could simply put an incorrect URL into the URL attribute of the AJAX call.
您可以简单地将错误的 URL 放入 AJAX 调用的 URL 属性中。
回答by Mild Fuzz
What I do is just turn my server off before I make the AJAX request, which will simulate the server not responding.
我所做的只是在发出 AJAX 请求之前关闭我的服务器,这将模拟服务器没有响应。
Remember it'll need to be switched back on before you can refresh for changes.
请记住,在刷新更改之前需要重新打开它。
回答by gerky
回答by Obinwanne Hill
If your URL is a PHP page, you can do something like this:
如果您的 URL 是 PHP 页面,您可以执行以下操作:
<?php
header("HTTP/1.0 404 Not Found");
exit();
//the rest of your code
You can simply comment it out later when you're done testing your error function.
您可以稍后在完成错误函数测试后简单地将其注释掉。