在jquery中通过AJAX和回调循环

我正在使用jquery和回调函数进行AJAX调用以检索AJAX调用之外的结果,并且我在尝试使用循环打印出来自此处提供的json文件(ticker.json)的更多数据时遇到问题:

{ "test": { "msgOne": [ "Remote One", "Remote Two", "Remote Three" ], "msgTwo": "Remote2", "msgThree": "Remote3" } } 

我的代码也在下面:

   Weather Data for Emergency Models     function hmm(callback) { $.ajax({ url : 'ticker.json', // ___ |I want to loop this dataType: 'json', // | |index as a variable success: function(response) { // v result = response['test']['msgOne'][2]; callback(result); } }); } hmm(function(result) { document.write(result); //currently outputs as "Remote Three" });    

主要问题是我想继续使用回调函数进行异步,并循环遍历json文件中的“msgOne”数组,并按顺序将所有三个结果打印到网页。 我曾尝试在以前的多个地方引入for循环,但我一直在收到错误。 我意识到还有其他方法可以做到这一点,但是在想要的条件下(异步和回调函数,因为我想最终将它应用于jsonp,用于列表中多个网站上的json文件),有没有办法做到这一点? 我最终想要修改给定的代码来处理数组和更复杂的代码。

试试这个 – 在你的success做到这一点

 success: function(response) { callback(response); } 

在你的function

 hmm(function(result) { $.each(result.test.msgOne,function(i,v){ document.write(v); }); }); 

试试这个假设响应[‘test’] [‘msgOne’]是一个数组

  success: function(response) { $.each(response['test']['msgOne'], callback); } hmm(function(i, result) { document.write(result); //currently outputs as "Remote Three" }); 
  $.ajax({ url : 'ticker.json', // ___ |I want to loop this dataType: 'json', // | |index as a variable success: function(response) { // v var result = response['test']['msgOne']; $.each(result,callback ). } }); function callback(index ,data){ document.write(data); } 

这有助于我遍历div行,提取他们的data-id属性并使用该数据id从ajax调用中检索数据。 恰好有40多个ajax调用通过itterate。 我必须让它们保持异步,但是要调用这些调用,以免使服务器过载。 我还使用PHP来检索缓存数据并将PHP缓存数组转换为javascript对象:

  public static function load_footer_js_css() { $screen = get_current_screen(); $whitelist = array('post','page'); if(!isset($screen) || !in_array($screen->post_type , $whitelist )) { return; } $transient = get_transient( 'inbound_ga_post_list_cache' ); $js_array = json_encode($transient); ?>