JSONP回调将结果分配给上下文

时间:2013-04-04 05:59:15

标签: callback jsonp

我正在尝试使用Apple搜索API来收集两个应用的名称,并用它替换原始的iTunes链接。但我的代码似乎只是一个接一个地用应用程序名称替换第二个iTunes链接。我有一种感觉它与回调有关,但我是一个菜鸟......所以有人可以帮助我。

这是我的代码:

<div class = "appinfo">https://itunes.apple.com/us/app/rock-runners/id575506874?mt=8></div>

<div class = "appinfo">https://itunes.apple.com/en/app/anomaly-warzone-earth-hd/id431607423?mt=8</div>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>

<script>
    window.onload = function injectAppInfoBlocks()
    {
        this.appInfoBlocks = document.getElementsByClassName('appinfo');


        if(appInfoBlocks) {
            for(var i=0; i<appInfoBlocks.length; i++) {
                currentAppId = appInfoBlocks[i].innerHTML.match(/id(\d+)/)[1];
                this.currentBlockId = i;
                var self = this;

                $.ajax( "https://itunes.apple.com/lookup?id=" + currentAppId, { 
                       dataType: "jsonp",
                       context: self,
                       success: function () {
                        name = arguments[0].results[0].trackName;
                        self.appInfoBlocks[self.currentBlockId].innerHTML=name;

                       }
                });
            }
        }

    }
</script>

不使用自己:

<div class = "appinfo">https://itunes.apple.com/us/app/rock-runners/id575506874?mt=8></div>

<div class = "appinfo">https://itunes.apple.com/en/app/anomaly-warzone-earth-hd/id431607423?mt=8</div>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>

<script>
    window.onload = function injectAppInfoBlocks()
    {
        appInfoBlocks = document.getElementsByClassName('appinfo');


        if(appInfoBlocks) {
            for(var i=0; i<appInfoBlocks.length; i++) {
                currentAppId = appInfoBlocks[i].innerHTML.match(/id(\d+)/)[1];
                currentBlockId = i;

                $.ajax( "https://itunes.apple.com/lookup?id=" + currentAppId, { 
                       dataType: "jsonp",
                       success: function () {
                        name = arguments[0].results[0].trackName;
                        appInfoBlocks[currentBlockId].innerHTML=name;

                       }
                });
            }
        }

    }
</script>

我也有一种感觉我不需要使用currentBlockID将“i”传递给回调函数但是......我不知道怎么做。

提前致谢!

0 个答案:

没有答案