代码之家  ›  专栏  ›  技术社区  ›  Jimmy

无法在jqueryajax中实现延迟承诺

  •  0
  • Jimmy  · 技术社区  · 7 年前

    报表.js

    function getReport(ref)
    {
       $.ajax({
            url: "report.php", 
            dataType: 'json',
            data: { 
                ref: ref,
            },
            success: function(result){
               return (result);
               }
             }
        });
    }
    

    索引.html

    <script>
    function firstFunction() {
    console.log ("start");
    getReport(2, 'queue', 'hour', '2018-09-09', '2018-09-10', 'pageviews', 'page', 's1390_5bbb4639ff37');
    };
    var test = firstFunction();
    alert(test);
    </script>
    

    目前,我得到“undefined”直接返回,因为警报框不等待ajax函数运行。使用一些在线教程,我尝试通过以下方式实现:

    报表.js

    function getReport(ref)
    {
       var deferred = $.Deferred();
       $.ajax({
            url: "report.php", 
            dataType: 'json',
            data: { 
                ref: ref,
            },
            success: function(result){
               deferred.resolve(result);
               }
             }
        });
      returned deferred.promise();
    }
    

        <script>
        function firstFunction() {
        console.log ("start");
        getReport(2, 'queue', 'hour', '2018-09-09', '2018-09-10', 'pageviews', 'page', 's1390_5bbb4639ff37');
        };
    $.when(getData()).done(function(value) {
        alert(value);
    });
    
    getData().then(function(value) {
        alert(value);
    });
    </script>
    

    很明显,我在路上犯了一些错误,因为我犯了下面的错误,我似乎无法克服:

    Uncaught SyntaxError: Unexpected identifier
    index2.html:12 start
    index2.html:13 Uncaught ReferenceError: getReport is not defined
        at firstFunction (index2.html:13)
        at index2.html:16
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Kamil Jarosz    7 年前

    deferred getReport中的对象是不必要的,因为 $.ajax 已经为您创建了一个。最好这样修改原始代码:

    function getReport(ref)
    {
       return $.ajax({ // Return the deferred object here. It is returned by .ajax()
            url: "report.php", 
            dataType: 'json',
            data: { 
                ref: ref,
            } // Remove the callback here. 
              // You cannot call return in the way you're trying here. 
              // The context is different and outside of normal flow.
        });
    }
    

    <script>
    function firstFunction() {
      console.log ("start");
      // You must return the returned value here as well, otherwise variable `test` is going to be undefined.
      return getReport(2, 'queue', 'hour', '2018-09-09', '2018-09-10', 'pageviews', 'page', 's1390_5bbb4639ff37');
    };
    var test = firstFunction(); // test is now a deferred object
    test.done(function(data) {
      alert(data);
    });
    </script>