在jquery中通过AJAX和回调循环

时间:2013-05-15 19:32:00

标签: javascript ajax jquery

我正在使用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文件),有没有办法做到这一点?我最终想要修改给定的代码来处理数组和更复杂的代码。

4 个答案:

答案 0 :(得分:0)

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

 success: function(response) {
                  $.each(response['test']['msgOne'], callback);
            }



hmm(function(i, result) {
        document.write(result);  //currently outputs as "Remote Three"
    });

答案 1 :(得分:0)

试试这个 - 在success

中执行此操作
success: function(response) {      
  callback(response);
}

并在function

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

这有助于我遍历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);


        ?>
        <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
    }