喵-见缝插针 2016-05-27 18:56 采纳率: 0%
浏览 48

AJAX偶尔无法使用

I am trying to make a chrome extension which fetches IDs of Youtube videos, but am facing a problem. For first execution, the AJAX call gives me an error, but for all subsequent calls, works just fine. This happens every time I open the extension. I am new to the scene, and hence, please excuse me for any rookie mistakes. My code :-

function getIDs(data){
    var items = [];
    for(i in data.items){
        items.push(data.items[i].id.videoId.toString());
    }
    for(i in items){
        $('<p>'+items[i]+'</p><br>').appendTo('#results');
    }
}

function getVideo(searchQuery){
    searchQuery = searchQuery.replace(/ /g,'+');
    var queryURL = 'https://www.googleapis.com/youtube/v3/search?q='+searchQuery+'&key=AIzaSyDq5SqWuQIEfIx7ZlQyKcQycF24D8mW798&part=snippet&maxResults=3&type=video';
    $.ajax({
        url: queryURL,
        dataType: 'json',
        success: function(data) {   
            getIDs(data);
        },
        error: function(ts){
            alert(ts.responseText);
        }
    });
}

document.addEventListener('DOMContentLoaded',function(){
    var button = document.getElementById('search');
    var div = document.getElementById('results');
    button.addEventListener('click',function(){
        var input = document.getElementById('input');
        var result = input.value;
        getVideo(result);
    });
});

I can't for the life of me figure out what is wrong. Thanks for the help in advance.

EDIT

I forgot to mention, but it gives me an undefined error. Sorry !!

  • 写回答

2条回答 默认 最新

  • python小菜 2016-05-27 19:14
    关注

    Your problem seems to be that the data you're retrieving doesn't load in time in the first execution since AJAX calls are asynchronous. So when you call getIDs(data), data might not be loaded yet (which is why it's working on the subsequent calls).

    One way you can resolve this issue is by using a promise. Rather than using success, you can do something like this:

        var ids; 
    
        $.ajax({
            url: queryURL,
            dataType: 'json',
            success: function(data) {   
                ids = data;
            },
            error: function(ts){
                alert(ts.responseText);
            }
        }).then(function(){   
                getIDs(ids); //calls this function *after* the data is retrieved
            });
    

    This post on StackOverflow does a good job of explaining it.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用