【问题标题】:Looping through AJAX and callbacks in jquery在jQuery中循环AJAX和回调
【发布时间】:2013-05-15 19:31:59
【问题描述】:

我目前正在使用 jquery 和回调函数进行 AJAX 调用,以检索 AJAX 调用之外的结果,我在尝试使用循环从我提供的 json 文件 (ticker.json) 中打印出更多数据时遇到了麻烦这里:

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

我的代码也在下面:

<html>
<head>
<title>Weather Data for Emergency Models</title>
<script src="jquery-1.9.1.min.js" type="text/javascript"></script> 
</head>

<body>
<script Language="JavaScript">

    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"
    });


</script>
</body>
</html>

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

【问题讨论】:

    标签: javascript ajax jquery


    【解决方案1】:

    试试这个 - 在您的 success 中执行此操作

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

    在你的function

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

    【讨论】:

    • 还有一个问题:如果我想循环 AJAX 调用以获取代表我的 URL 的数组,我该怎么做? (假设URL的json文件结构相同,只是名称不同)
    • loop through the AJAX call ?我没有得到你想要的。可以举个例子说的更清楚吗
    • 是的,假设我有一个名为 myURL 的预定数组,并且我想循环通过 ajax 调用,这样每次 ajax 调用发生时,都会使用与 myURL 不同的 url,从而产生不同的回调中的响应。
    • 这很容易做到。但是我无法更新我的答案,因为这似乎与您的问题无关,尽管我建议您发布一个新问题并提供链接,以便我可以在那里回答。
    • 试试这个:stackoverflow.com/questions/16574047/… 并提前感谢您的帮助。
    【解决方案2】:

    试试这个 假设 response['test']['msgOne'] 是一个数组

     success: function(response) {
                      $.each(response['test']['msgOne'], callback);
                }
    
    
    
    hmm(function(i, result) {
            document.write(result);  //currently outputs as "Remote Three"
        });
    

    【讨论】:

      【解决方案3】:
          $.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);
        }
      

      【讨论】:

        【解决方案4】:

        这帮助我遍历 div 行,提取它们的 data-id 属性并使用该数据 id 从 ajax 调用中检索数据。碰巧有 40 多个 ajax 调用需要迭代。我必须让它们异步为真,但要使调用失败,以免服务器超载。我还使用 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);
        
        
                ?>
                <script type="text/javascript">
                    <?php
                    echo "var cache = JSON.parse('". $js_array . "');\n";
                    ?>
        
                    function inbound_ga_listings_lookup( cache, post_ids, i , callback , response ) {
        
                        if (!post_ids[i]){
                            return true;
                        }
        
                        if (typeof response == 'object' && response  ) {
                            jQuery('.td-col-impressions[data-post-id="' + post_id + '"]').text(response['impressions']['current']['90']);
                            jQuery('.td-col-visitors[data-post-id="' + post_id + '"]').text(response['visitors']['current']['90']);
                            jQuery('.td-col-actions[data-post-id="' + post_id + '"]').text(response['actions']['current']['90']);
                        }
        
                        if (i == 0) {
                            post_id = post_ids[0];
                            i++;
        
                        } else {
                            post_id = post_ids[i];
                            i++;
                        }
        
                        if (typeof cache[post_id] != 'undefined') {
                            jQuery( '.td-col-impressions[data-post-id="' + post_id + '"]').text( cache[post_id].impressions.current['<?php echo self::$range; ?>'] );
                            jQuery( '.td-col-visitors[data-post-id="' + post_id + '"]').text(cache[post_id].visitors.current['<?php echo self::$range; ?>']);
                            jQuery( '.td-col-actions[data-post-id="' + post_id + '"]').text(cache[post_id].actions.current['<?php echo self::$range; ?>']);
                        } else {
                            jQuery.ajax({
                                type: "POST",
                                url: ajaxurl,
                                data: {
                                    action: 'inbound_load_ga_stats',
                                    post_id: post_id
                                },
                                dataType: 'json',
                                async: true,
                                timeout: 10000,
                                success: function (response) {
        
                                    callback(cache, post_ids, i, callback , response);
                                },
                                error: function (request, status, err) {
                                    response['totals'] = [];
                                    response['totals']['impressions'] = 0;
                                    response['totals']['visitors'] = 0;
                                    response['totals']['actions'] = 0;
                                    callback(cache, post_ids, i, callback , response);
                                }
                            });
                        }
                    }
        
                    jQuery(document).ready( function($) {
        
                        var post_ids = [];
                        var i = 0
                        jQuery( jQuery('.td-col-impressions').get() ).each( function( $ ) {
                            var post_id = jQuery(this).attr('data-post-id');
                            post_ids[i] = post_id;
                            i++;
                        });
        
                        inbound_ga_listings_lookup( cache, post_ids, 0 , inbound_ga_listings_lookup , null );
                });
                </script>
                <?php
            }
        

        【讨论】:

          猜你喜欢
          • 2012-03-03
          • 1970-01-01
          • 2015-04-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-27
          相关资源
          最近更新 更多