weixin_33691817 2018-10-13 16:42 采纳率: 0%
浏览 20

如何模拟一个ajax响应

How can one mock an ajax response?

https://stackoverflow.com/a/13915248/1032531 provides a link to an answer but the link is broken.

https://stackoverflow.com/a/29680013/1032531 provides the following answer but it errors with $.ajax is not a function. https://jsfiddle.net/bdw0gfan/

 function ajax_response(response) {
   var deferred = $.Deferred().resolve(response);
   return deferred.promise();
 }
 $(function() {

   $.ajax = ajax_response([1, 2, 3]);
   $.ajax('GET', 'some/url/i/fancy').done(function(data) {
     console.log(data); // [1, 2, 3]
   });
 });
  • 写回答

1条回答 默认 最新

  • weixin_33720956 2018-10-13 16:47
    关注

    $.ajax needs to be a function or else it won't return the promise.

    function ajax_response(response) {
        var deferred = $.Deferred().resolve(response);
        return deferred.promise();
    }
    
    $.ajax = function() {
        return ajax_response([1, 2, 3]); 
    };
    
    $.ajax('GET', 'some/url/i/fancy').done(function(data) {
        console.log(data); // [1, 2, 3]
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    </div>
    
    评论

报告相同问题?