遍历AJAX和jquery中的回调

遍历AJAX和jquery中的回调

本文介绍了遍历AJAX和jquery中的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently doing an AJAX call with jquery and callback functions to retrieve a result outside of the AJAX call and I am having trouble in attempting to use a loop to printout more data from my json file (ticker.json) provided here:

{
    "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循环,但我一直遇到错误.我意识到还有其他方法可以执行此操作,但是在需要的条件下(异步和回调函数,因为我希望最终将此方法应用于列表中多个网站上找到的json文件的jsonp),是否可以执行此操作?我最终想要修改给定的代码以处理数组和更复杂的代码.

The main problem is that I want to continue as asynchronous using the callback functions and loop through the "msgOne" array in the json file and print out all three results to the webpage sequentially. I have tried introducing a for-loop in multiple places previously, but I keep getting errors. I realize there are other ways to do this, but under the wanted conditions (asynchronous & callback functions because I want to eventually apply this to jsonp for json files found on multiple websites on a list), is there a way to do this? I ultimately want to modify the given code to deal with arrays and more complex code.

推荐答案

尝试一下-在您的success

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

和您的function

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

这篇关于遍历AJAX和jquery中的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 04:45