简体   繁体   English

嵌套 ajax 调用的最佳实践

[英]Best practice for nesting ajax calls

I am creating a simple app using Spotify REST API and JQuery where users can find an artist, and then it will show info about the artist, related artists, and most listened to songs on-page.我正在使用 Spotify REST API 和 JQuery 创建一个简单的应用程序,用户可以在其中找到艺术家,然后它将在页面上显示有关艺术家、相关艺术家和收听次数最多的歌曲的信息。 I created 3 ajax calls which u can see below and everything works, but I think that it can be written in a better way (promises maybe?).我创建了 3 个 ajax 调用,您可以在下面看到并且一切正常,但我认为它可以以更好的方式编写(可能是承诺?)。

The first ajax call gets id from the server and create some DOM elements.第一个 ajax 调用从服务器获取 id 并创建一些 DOM 元素。 The second two ajax calls need id to run and also create DOM elements.后两个 ajax 调用需要 id 才能运行并创建 DOM 元素。 There is also a delete button that should delete DOM elements built from the data of each ajax call.还有一个删除按钮应该删除从每个 ajax 调用的数据构建的 DOM 元素。

Is it possible to have it nested using the best practice or this is the only way possible?是否可以使用最佳实践将其嵌套,或者这是唯一可能的方法?


    artistForm.submit((e) => {
    e.preventDefault();
    let inputSearchQuery = artistInput.val();
    let searchQuery = encodeURI(inputSearchQuery);

    $.ajax({
        url: `${baseUrl}search?q=${searchQuery}&type=artist`,
        type: 'GET',
        datatype: 'json',
        headers: {
            'Authorization': 'Bearer ' + accessToken
        }
    }).done((resp) => {

        
        const artistId = (resp.artists.items[0].id);
        // working with data and appending them on DOM


        $.ajax({
            url: `${baseUrl}artists/${artistId}/top-tracks?country=CZ`,
            type: 'GET',
            datatype: 'json',
            headers: {
                'Authorization': 'Bearer ' + accessToken
            }
        }).done((resp) => {

            // working with data and appending them on DOM

            $.ajax({
                url: `${baseUrl}artists/${artistId}/related-artists`,
                type: 'GET',
                datatype: 'json',
                headers: {
                    'Authorization': 'Bearer ' + accessToken
                }
            }).done((resp) => {

                // working with data and appending them on DOM

                deleteArtist.click(() => {
                   // need to have acces to data from every ajax call.

                })

            });
        });
    });
});

Given your work case, you could consider the following method:鉴于您的工作案例,您可以考虑以下方法:

artistForm.submit(async (e) => {
    e.preventDefault();
    let inputSearchQuery = artistInput.val();
    let searchQuery = encodeURI(inputSearchQuery);

    let artist = await $.ajax({
        url: `${baseUrl}search?q=${searchQuery}&type=artist`,
        type: 'GET',
        datatype: 'json',
        headers: {
            'Authorization': 'Bearer ' + accessToken
        }
    });

    const artistId = artists.items[0].id;
    let topTracks = await $.ajax({
        url: `${baseUrl}artists/${artistId}/top-tracks?country=CZ`,
        type: 'GET',
        datatype: 'json',
        headers: {
            'Authorization': 'Bearer ' + accessToken
        }
    });

    let relatedArtists = await $.ajax({
        url: `${baseUrl}artists/${artistId}/related-artists`,
        type: 'GET',
        datatype: 'json',
        headers: {
            'Authorization': 'Bearer ' + accessToken
        }
    });

    deleteArtist.click(() => {
        // need to have access to data from every ajax call.
    });
});

This is assuming you are using jQuery 3.0 or higher.这是假设您使用的是 jQuery 3.0 或更高版本。 If not you can find a nice wrapper function here .如果没有,您可以在这里找到一个不错的包装器 function。

If you want to learn more about promises and async await I recommend the following video's: JavaScript Promises In 10 Minutes - by Web Dev Simplified and The Async Await Episode I Promised - by Fireship .如果您想了解有关承诺和异步等待的更多信息,我推荐以下视频: JavaScript Promises In 10 Minutes - by Web Dev SimplifiedThe Async Await Episode I Promised - by Fireship

If you have questions about the code above, please add a comment.如果您对上面的代码有任何疑问,请添加评论。

I hope this helps you continue with your project (and that you've learn something along the way ).我希望这可以帮助您继续您的项目(并且您在此过程中学到了一些东西)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM