簡體   English   中英

無法在jquery ajax中實現延遲的Promise

[英]Can't implement deferred promise in jquery ajax

我正在努力實現推遲以獲得異步ajax響應。 我有這個設置:

report.js

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

的index.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>

當前,由於警報框不等待ajax函數運行,我立即返回“ undefined”。 使用一些在線教程,我試圖通過這種方式實現它:

report.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();
}

的index.html

    <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

我認為沒有必要在getReport中添加deferred對象,因為$.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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM