使用ajax的承诺不会在jquery中返回任何值

时间:2016-07-25 14:38:27

标签: javascript jquery ajax

我的剧本:

var testApp = (function($){
    var data = [{
        "layout": "getSample",
         "view": "conversations",
         "format": "json",
    }];

    var Data = 'default';
    function ajaxCall(opt) {
        return new Promise(function(resolve, reject) {

            jQuery.ajax({

               method: "POST",
               url: localStorage.getItem("root")+"/index.php",
               "data": opt,
               error: function() {
                   alert('error');
               },  
               success: function(result) {
                   console.debug(result);
                   resolve(result);

               }//end success
          });//end ajax

       });//end promise
    }
    return {

        render: function(opt) {
            if(typeof opt === 'object') {
                var list = {
                    data : [opt]
                }

                //here I'm passing list object's data to be used in ajaxCall function.That's the reeason I used call method. It's data is passed from another page.
                ajaxCall.call (list, list.data).then(function(v) { 
                    console.log("v "+v); // nothing happens yet...expecting for the success object to be passed here
                }).catch(function(v) {
                    //nothing to do yet
                });


            }
        }

    };//end return
})(jQuery);

使用带有ajax的promise的正确方法是什么?

ajaxCall.call (list, list.data).then(function(v) { 
 console.log("v "+v); // doesn't return anything
}).catch(function(v) {
//nothing to do yet
});

提到:How do I return the response from an asynchronous call?

2 个答案:

答案 0 :(得分:0)

好吧,我找到了一个简单的修复方案.. //下面的代码行,移到上面,返回新的承诺并且有效

var opt = jQuery.extend({},data [0],opt [0]);

答案 1 :(得分:0)

jQuery Ajax函数已经返回promises。你不必手动将它们变成承诺。

var testApp = (function($) {
    var ajaxDefaults = {
        "layout": "getSample",
        "view": "conversations",
        "format": "json",
    };

    // this can be re-used in all your Ajax calls
    function handleAjaxError(jqXhr, status, error) {
        console.error('Ajax error', error);
    });

    function ajaxCall(opt) {
        var url = localStorage.getItem("root") + "/index.php",
            data = jQuery.extend({}, ajaxDefaults, opt);

        return $.post(url, data).fail(handleAjaxError);
    }

    return {
        render: function(opt) {
            return ajaxCall(opt).then(function (result) {
                console.log("v " + result);
                return result;
            });
        }
    };
})(jQuery);
  • 您不需要使用.call()来调用函数。在这种情况下,它也没有多大意义。如果它不是对象方法,而是独立函数,则通常调用它并传递参数。
  • 无法保证localStorage.getItem("root")包含任何值,但您的代码忽略了这种可能性。这是一个错误。
  • 您不希望代码中有两个变量dataData。不要像这样设置旅行线。
  • $.ajax() / $.post()可以在一行中完成工作时,无需使用$.get()
  • 也可以从render()方法及其.then()处理程序返回一些内容,这样您就可以在应用程序的其他位置链接更多代码,例如

    app.render({data: 1234}).then(function (result) {
        // ...
    });
    
相关问题