2016-07-31 76 views
1

我正在嘗試修改一個Wordpress插件,以便它不會頻繁執行admin-ajax.php腳本。該插件在頁面上顯示輪詢 - 它在文檔準備就緒後異步加載它們。有問題的腳本是下面寫的async-load.js。現在.load在for循環中用於顯示頁面上的每個輪詢(每個頁面有多個輪詢)。這會爲頁面上的每個輪詢執行admin-ajax腳本 - 例如,如果有10次輪詢腳本被執行了10次。Jquery .load - 同時具有不同數據的多個ID - Wordpress

我想知道是否可以修改腳本,以便它只顯示一個admin-ajax.php腳本執行的所有輪詢。

這裏是全碼:

if (window['tp_async_polls']) { 
jQuery(document).ready(function ($) { 

    var pollContainer = []; 
    var pollID = []; 

    $(tp_async_polls).each(function (index, poll) { 
     //tp_async_polls gives an array of object with keys id and container 
     pollContainer.push(poll.container); 

     //store each poll's container id in array 

     pollID.push(poll.id); 

     //store each poll's id in array 
    }); 

for (i=1; i < pollContainer.length; i++) { 

    //loop through polls and display them - here the admin-ajax.php gets executed for every poll that is on a page. Looking for solution to only execute it once per page load. 
     $(pollContainer[i]).load(totalpoll_cache_compatibility.ajaxurl, {action: 'load_tp', tp_poll_id: pollID[i]}, function() { 

      FastClick.attach(this); 
      $(this).animateVotesBar(); 
     }); 
    }; 
}); 

};

任何建議是值得歡迎的。謝謝你的幫助。

回答

0

這只是你應該做的一般想法,它是不是一個工作示例。

在您的示例中,變量pollIDArray,其中包含所有投票的ID。

取代循環遍歷所有容器並請求每個容器的內容,您可以發送1個帶有ID列表(pollID)的請求,並且一旦收到數據 - 您就可以相應地更新投票。

讓我們請求的數據應該從

{action: 'load_tp', tp_poll_id: pollID[i]} 

改爲類似

{action: 'load_tps', all_poll_ids: pollID} 

在你的服務器中的代碼應該返回是這樣的:

{ 
    165 : '<div> CONTENT OF HTML FOR POLL ID = 165</div>', 
    179 : '<div> CONTENT OF HTML FOR POLL ID = 179</div>', 
    .... 
} 

你也可以發送請求使用$.ajax,看起來像這樣:

$.ajax({ 
    type: "POST", 
    url: totalpoll_cache_compatibility.ajaxurl, 
    data: {action: 'load_tps', all_poll_ids: pollID}, 
    success: function(data) { 
     $.each(data, function(poll_id, poll_html) { 
      $(pollContainer[poll_id]).html(poll_html) 
      ... 
     }); 
    } 
    ... 
}); 
相關問題