使用Promise规定来处理ajax请求的结果

ajax()返回结果是成功的,调用done()中的回调函数;

失败则调用fail()中的回调函数;

always()的回调函数不管成功是否都会调用;

可以是使用then()函数代替done()和fail(),then()有两个参数,

一个是aja请求成功的回调函数,另外一个则是失败的回调函数。

demo如下:

<script>
$(document).ready(function() {
  $('#trigger').click(function() {
    $.ajax({url:'test.json', dataType: 'json'})
    .done( function(data) {
      $('#target').append('The returned value is: ' 
                            + data.name + '<br>');
    })
    .fail(function() {
      $('#target').append('The AJAX call failed.<br>');
    })
    /*
        .then(
            function(data) {
                $('#target').append('The returned value is: ' 
                            + data.name + '<br>');
            },
            function() {
                $('#target').append('The AJAX call failed.<br>');
            }
        )
    */
        
        
    .always(function() {
      $('#target').append('finished anyway.');
    });
  });
});
</script>
原文地址:https://www.cnblogs.com/scnuwangjie/p/4965926.html