jQuery $.ajax 错误函数不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18997341/
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
$.ajax error function is not working
提问by Yup
I'm working on some existing code. I have the following code:
我正在处理一些现有的代码。我有以下代码:
$.ajax({
type: "get",
url: url ,
dataType: "jsonp",
cache: "false",
jsonpCallback: "onJSONPLoad",
success: function(json){
alert('hi!');
//perform operation
},
error: function() {
alert('Error occurs!');
}
});
Now when I'm passing valid url
it works fine. But when I'm passing invalid url
it should through an error alert. But the script is not throwing any error alert. Basically I want validate the url
parameter or it is failing? Please help me to find-out the error in my code or suggest me else way to achieve. I have checked the following links but not able to solve my problem:
现在,当我通过有效时,url
它工作正常。但是当我传递无效时,url
它应该通过错误警报。但是脚本没有抛出任何错误警报。基本上我想验证url
参数还是失败了?请帮助我找出代码中的错误或建议我以其他方式实现。我检查了以下链接,但无法解决我的问题:
jQuery Ajax error handling, show custom exception messages
jQuery ajax error function,
Ajax Success and Error function failure
jQuery Ajax 错误处理,显示自定义异常消息
jQuery ajax 错误函数,
Ajax 成功和错误函数失败
UPDATE:I have added below code to log the jquery console log.
更新:我添加了以下代码来记录 jquery 控制台日志。
@Override
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.d("web chrome client", cm.message() + " -- From line "
+ cm.lineNumber() + " of "
+ cm.sourceId() );
return true;
}
Identified the following error:
XMLHttpRequest cannot load file:///android_asset/xxxx/new_source.json?callback=onJSONPLoad. Origin null is not allowed by Access-Control-Allow-Origin. -- From line 1 of null
识别出以下错误:
XMLHttpRequest cannot load file:///android_asset/xxxx/new_source.json?callback=onJSONPLoad. Origin null is not allowed by Access-Control-Allow-Origin. -- From line 1 of null
Adding the following code, app is running successfully.
添加以下代码,app运行成功。
if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
}
So, basically this is happening as the url is not accessible by the jquery.
Thanks every body for helping me.
所以,基本上这是因为 jquery 无法访问 url。
感谢每一个人帮助我。
回答by Shakti Patel
used this
用过这个
1)replace this: dataType: jsonpfor cross-domain request, that means request to different domain and
1) 替换这个: dataType: jsonp用于跨域请求,这意味着请求到不同的域和
dataType: jsonfor same domain-same origin request. dataType: "json"
dataType:同域同源请求的json。 数据类型:“json”
2)You are missing ',' after successfunction
2)您在成功功能后缺少“,”
$.ajax({
type: "get",
url: url ,
dataType: "json",
cache: "false",
jsonpCallback: "onJSONPLoad",
success: function(json){
alert('hi!');
//perform operation
},
error: function() {
alert('Error occurs!');
}
});
3) try this
3)试试这个
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
4) check this jQuery.ajax
4) 检查这个jQuery.ajax
The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data. To do so, it uses jQuery.parseJSON() when the browser supports it; otherwise it uses a Function constructor. Malformed JSON data will throw a parse error (see json.org for more information). JSON data is convenient for communicating structured data in a way that is concise and easy for JavaScript to parse. If the fetched data file exists on a remote server, specify the jsonp type instead.
json 类型将获取的数据文件解析为 JavaScript 对象,并将构造的对象作为结果数据返回。为此,它在浏览器支持时使用 jQuery.parseJSON();否则它使用函数构造函数。格式错误的 JSON 数据将引发解析错误(有关更多信息,请参阅 json.org)。JSON 数据便于以简洁且易于 JavaScript 解析的方式传达结构化数据。如果获取的数据文件存在于远程服务器上,请改为指定 jsonp 类型。
The jsonp type appends a query string parameter of callback=? to the URL. The server should prepend the JSON data with the callback name to form a valid JSONP response. We can specify a parameter name other than callback with the jsonp option to $.ajax().
jsonp 类型附加了一个 callback=? 到网址。服务器应该在 JSON 数据前面加上回调名称以形成有效的 JSONP 响应。我们可以使用 $.ajax() 的 jsonp 选项指定回调以外的参数名称。
Note: JSONP is an extension of the JSON format, requiring some server-side code to detect and handle the query string parameter. More information about it can be found in the original post detailing its use.
注意:JSONP 是 JSON 格式的扩展,需要一些服务器端代码来检测和处理查询字符串参数。有关它的更多信息可以在详细介绍其用途的原始帖子中找到。
When data is retrieved from remote servers (which is only possible using the script or jsonp data types), the error callbacks and global events will never be fired.
当从远程服务器检索数据时(只能使用脚本或 jsonp 数据类型),永远不会触发错误回调和全局事件。
but you need to fire then code :
但你需要触发然后代码:
var req = $.ajax({
url : url,
dataType : "jsonp",
timeout : 10000
});
req.success(function() {
console.log('Yes! Success!');
});
req.error(function() {
console.log('Oh noes!');
});
回答by Swapnil Patil
You are missing comma after success function and also change dataType to json
您在成功功能后缺少逗号,并且还将 dataType 更改为 json
$.ajax({
type: "get",
url: url ,
dataType: "json",
cache: "false",
jsonpCallback: "onJSONPLoad",
success: function(json){
alert('hi!');
//perform operation
},
error: function() {
alert('Error occurs!');
}
});
回答by Ludovic Pollet
A bug recently introduced in chrome 52 (august 2016) can also cause this kind of behavior. Hoppefully, it will not last long.
最近在 chrome 52(2016 年 8 月)中引入的一个错误也可能导致这种行为。希望它不会持续太久。
https://bugs.chromium.org/p/chromium/issues/detail?id=633696
https://bugs.chromium.org/p/chromium/issues/detail?id=633696
It is not strictly related to the initial problem because it triggers only for GET request started from the onSuccess handler, but I mention it for others who may search help on this problem.
它与最初的问题并不严格相关,因为它仅在从 onSuccess 处理程序启动的 GET 请求时触发,但我提到它是为了其他可能会搜索此问题帮助的人。
回答by Puzzled Boy
Try with this.
试试这个。
$.ajax({
type: "get",
url: url ,
dataType: "jsonp",
cache: "false",
jsonpCallback: "onJSONPLoad",
success: function(result){
alert('hi!');
//perform operation
},
error: function( req, status, err ) {
console.log( 'something went wrong', status, err );
alert('something went wrong'+ status + err);
}
});
Also read this. http://api.jquery.com/jQuery.getJSON/#entry-examples
也读这个。 http://api.jquery.com/jQuery.getJSON/#entry-examples
and try
$.getJSON()
instead of $.ajax()
并尝试
$.getJSON()
代替$.ajax()