Lee*_*eem 41 javascript ajax jquery spring
通过使用jquery ajax函数,我可以做类似的事情:
$.ajax({
url: url,
type: 'GET',
async: true,
dataType: 'json',
data: data,
success: function(data) {
//Handle server response here
},
error: function(xhr, status, error){
//Handle failure here
}
});
Run Code Online (Sandbox Code Playgroud)
根据以上代码,我有两个问题要问:
什么时候error调用jquery.ajax()回调?
如果服务器使用字符串消息" 有错误 " 向我回复json对象怎么办?这意味着请求仍然成功发送,但我得到了服务器响应{message: "There is an error"}.
我认为无论服务器响应什么字符串值,如果客户端得到服务器的响应,无论如何都会触发jquery.ajax() success回调.
我想问一下服务器是否特意向我返回一个字符串值为的JSON对象{message: 'There is an error'},服务器可以执行某些操作以便可以在jquery.ajax() error回调而不是success回调中处理此响应吗?
RaY*_*ell 33
当服务器的响应不符合您的预期时,将执行错误回调.例如,在这种情况下,它:
在您的情况下,数据是正确的(这是一个JSON消息).如果要根据接收数据的值手动触发错误回调,则可以非常简单地完成.只需将错误的匿名回调更改为命名函数即可.
function handleError(xhr, status, error){
//Handle failure here
}
$.ajax({
url: url,
type: 'GET',
async: true,
dataType: 'json',
data: data,
success: function(data) {
if (whatever) {
handleError(xhr, status, ''); // manually trigger callback
}
//Handle server response here
},
error: handleError
});
Run Code Online (Sandbox Code Playgroud)
Sim*_*ken 26
我们假设服务器正在发送JSON,如果请求成功,我们将得到如下内容:
{
success: true,
data: {
name: 'Foo'
}
}
Run Code Online (Sandbox Code Playgroud)
......并且失败了:
{
success: false,
error: 'Something bad happened.'
}
Run Code Online (Sandbox Code Playgroud)
然后我们只需使用$ .Deferred过滤响应:
$.get('http://localhost/api').then(function(res) {
var filter = $.Deferred();
if (res.success) {
filter.resolve(res.data);
} else {
filter.reject(res.error);
}
return filter.promise();
}).done(function(data) {
console.log('Name:', data.name); // Outputs: Foo
}).fail(function(error) {
console.log('Error:', error); // Outputs: Something bad happened.
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46397 次 |
| 最近记录: |