简体   繁体   中英

[javascript]Use the data from 1st json and convert it to a variable and use that variable to call a 2nd json

Hello guys am new here but I have a problem and need your help, so in my code I called a json file.

var data = {};
var spectator;
var tmp = [];
var IDcatcher =[];
var summonerID = [];
$.getJSON(getUrl, function(data) {
            tmp = data;

            $.each(tmp, function(key){
                for (IDcatcher in tmp) {}

                });
            summonerID = tmp[IDcatcher].id;
        });

so this gives me the ID from the Json wich is stored in summonerID variabel now I want to use this variabel to complete the url to get the 2nd Json so..

var spectatorUrl = "link" + summonerID;

Now get the 2nd Json

var Charcatcher =[];
var CharID = [];
$.getJSON(spectatorUrl, function(data) {
        tmp = data;

        $.each(tmp, function(key){
            for (Charcatcher in tmp) {}

            });
        CharID = tmp[Charcatcher].id;
    });

My problem is the 2nd Json doesnt run, it doesn't get anything and returns nothing (obviously).

Help ? I cant run 2 jsons at diferent times ? If so how can I do it or change it ?

As I mentioned, due to the asynchronous nature of JavaScript, if you have an AJAX request with a callback and some code following the request, JS will fire off the AJAX request and will continue with the rest of the code. It won't wait for the result of the AJAX request to return.

Here's a simple demo -

 function first() { setTimeout(() => { console.log("1"); }, 2000); console.log("2"); }; first(); 

Look at the order of the console.log statements in the code, and then check the actual order in the console.

To solve your original problem, you can nest a $.getJSON() inside the first one, this will ensure that summonerID is available when you fire off the second AJAX request.

$.getJSON(getUrl, function(data) {
            tmp = data;

            $.each(tmp, function(key){
                for (IDcatcher in tmp) {}

                });
            summonerID = tmp[IDcatcher].id;

            // second AJAX request
            var spectatorUrl = "link" + summonerID;
            $.getJSON(spectatorUrl, function(data) {
               // logic
            });

        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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