我知道这可以用ajax完成,但我想知道如何使用get()快捷方式来完成...
鉴于此:
$.get('someurl.com', function(data, statusText, xhr) {
$('#sometag').html(data);
});
我怎么能对任何不是200的东西进行错误检查?如果请求有效但没有有用的数据要返回,我正在访问的api会定期返回204。
答案 0 :(得分:1)
小提琴链接 - http://jsfiddle.net/smegha11/6xu3K/
您可以使用xhr.status属性检查响应代码
$.get('someurl.com', function(data, statusText, xhr) {
if(xhr.status==200)
{
$('#sometag').html(data);
}
});
答案 1 :(得分:-1)
使用回调方法
The Promise interface also allows jQuery's Ajax methods, including $.get(), to chain
multiple .done(), .fail(), and .always() callbacks on a single request.
示例强>
$.get( "someurl.com", function() {
Console.log( "success" );
}).done(function() {
Console.log( "second success" );
}).fail(function() {
Console.log( "error" );
}).always(function() {
Console.log( "finished" );
});
检查 $get
的文档以下是每个功能正在接收的参数
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.
In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});
Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.
的文档