I want to take over the value of the variable that I counted up when I got JSON for subsequent processing.

Asked 2 years ago, Updated 2 years ago, 53 views

Thank you for your continuous support.I am a beginner at javascript.
Last time, I learned how to call json more when ajax succeeded.
This time, I want to take over the counted-up value in json after leaving json, but for some reason it doesn't work.

I apologize for the inconvenience, but please let me know.

Current Results → alert(j);
alert0
alert0
alert0
alert0
alert0
alert0
alert0
alert0

Desired Results → alert(j);

alert0
alert1
alert2
alert3
alert4
alert5
alert6
alert7

function Henka(){

    $.ajax({
        url: 'CSV Address',
        success:function(era){

            // json in csv
            csvListall=$.csv()(era);

            // definition of variable j
            varj = 0;

            // Add for minutes
            for(vari=0;i<264;i++){

                // Each variable definition;
                var calendarId=';
                varcalendarId=csvListall[i][2];
                varirank=';
                variablerank=csvListall[i][5];
                variableimg=';
                variiimg=csvListall[i][7];
                variname=';
                variname=csvListall[i][0];
                variable target=';
                variable target=csvListall[i][6];

                vartab='[data-today="'+j+']";
                varuri="https://www.googleapis.com/calendar/v3/calendars/"+calendarId+"/events?key="+apikey+"&timeMin="+timeMin+"&timeMax="+timeMax+"&maxResults=10&orderBy=startTime&singleEvents=true";
                varjsinfo=uri;

                // The point of the problem is ----------------------------------------------------------

                $.getJSON(jsinfo,
                    ( function(irank, iimg, iname, tab, target, j){
                        return function(data){
                            if(data.items[0].summary!=""){
                                // Count of processing count
                                j = j+1;
                                // Processing details
                                vivid='<img src='+iimg+'" alt="empty" style="height:150px;" class="app-button" data-target="'+target+'">br>'+iname+';;
                                $(tab).append(vivid);
                            }
                        };
                    }) (irank, iimg, iname, tab, target, j)
                );
                alert(j);

                // The point of the problem is ---------------------------------------------------------

            }
        }
    });
}

javascript json

2022-09-29 22:43

3 Answers

Answer

If you do the following, the img tag will probably be added to [data-today="0"] to [data-today="263"] in the order in which the JSON download is complete.

If you start with [data-today="1"], set the initial value of variable j to 1.
(Change to varj=1;)

function Henka(){
    $.ajax({
        url: 'CSV Address',
        success:function(era){
            // json in csv
            csvListall=$.csv()(era);

            // definition of variable j
            varj = 0;

            // Add a for statement
            for(vari=0;i<264;i++){

                // Each variable definition
                varcalendarId=csvListall[i][2];
                variablerank=csvListall[i][5];
                variiimg=csvListall[i][7];
                variname=csvListall[i][0];
                variable target=csvListall[i][6];

                varuri="https://www.googleapis.com/calendar/v3/calendars/"+calendarId+"/events?key="+apikey+"&timeMin="+timeMin+"&timeMax="+timeMax+"&maxResults=10&orderBy=startTime&singleEvents=true";

                $.getJSON(uri,
                    ( function(iimg, iname, target) {
                        return function(data){
                            if(data.items[0].summary!==""){
                                // Processing details
                                vartab='[data-today="'+j+']";
                                varvid='<img src='+img+'" alt="empty" style="height:150px;" class="app-button"data-target="'+target+'"/>br/>'+iname;
                                $(tab).append(vivid);

                                // Count of processing count
                                j = j+1;
                            }
                        };
                    }) (iimg, iname, target)
                );
            }
        }
    });
}

Explanation

The j in //process refers to the varj=0; value defined above the for statement.
Therefore, each time you finish downloading JSON, the // processing count is executed, and the number increases by 1.

Functions that reference variables that are defined outside themselves are referred to as closures.

In this example, the variable defined outside is j and the function with // processing referencing j is the closure.

Below are some of the codes in the question that bothered me.

    There are two definitions, such as
  • varirank, but the first definition is not necessary because the second time immediately after the first time the value was substituted.
    (You should define variables only once (var).
  • //The action does not use irank, so you do not need to pass it to (function(){})().
  • vivid is probably a local variable, so you should add var.
  • Generally, you should use === or !== to compare values.

Comparison operator - JavaScript|MDN

By the way

We have created the smallest code below that works the same way as the code you wrote in your answer.
If you are interested, please check it out.

varcsvListall=[
  [0, "sss", "//dummyimage.com/101x50/", "one", "target"],
  [1, "ss", "//dummyimage.com/102x50/", "two", "target"],
  [2, "s", "//dummyimage.com/103x50/", "three", "target"],
  [3, "a", "//dummyimage.com/104x50/", "four", "target"],
  [4, "b", "//dummyimage.com/105x50/", "five", "target"],
  [5, "c", "//dummyimage.com/106x50/", "six", "target"],
  [6, "sss", "//dummyimage.com/107x50/", "seven", "target"],
  [7, "ss", "//dummyimage.com/108x50/", "eight", "target"],
  [8, "s", "//dummyimage.com/109x50/", "nine", "target"],
  [9, "a", "//dummyimage.com/110x50/", "ten", "target"]
];

varj = 0;

for(vari=0;i<10;i++){
  var calendarId = csvListall[i][0];
  varrank=csvListall[i][1];
  varimg=csvListall[i][2];
  var name = csvListall[i][3];
  target=csvListall[i][4];

  // Asynchronous processing (assuming JSON downloads)
  setTimeout(function(img,name,target){
    return function(data){
      if(Math.random()>0.5){
        // Processing details
        varvid='<img src='+img+'" alt="empty" data-target='+target+'/>br/>'+name;
        $('[data-today='+j+']').append(vivid);
        j++;
      }
    }
  }) (img, name, target), 500);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div data-today="0"></div>
<div data-today="1"></div>
<div data-today="2"></div>
<div data-today="3"></div>
<div data-today="4"></div>
<div data-today="5"></div>
<div data-today="6"></div>
<div data-today="7"></div>
<div data-today="8"></div>
<div data-today="9"></div> 

If the value Math.random() that randomly generates a value between 0 and 1 is greater than 0.5, the process of adding an img tag will work.


2022-09-29 22:43

j=j+1; is a variable that is local to the function as an argument for an unknown function (function literal), so
Changes here do not affect the calling party of the function.

There may be many solutions, but
One way is to make it a reference type, so you can get the desired behavior.
For example, change varj=0; to
varj={counter:0};

j=j+1; to
Change to j.counter+=1;.
And
Change alert(j); to alert(j.counter);.


2022-09-29 22:43

Because $.getJSON is an asynchronous operation, an alert is performed before the callback completes and the count does not increase, and the callback does not always occur in the order in which $.getJSON is performed.Therefore, there is a possibility that the order of 'data-today' will be changed.If you think it's not desirable to have a different order, you need to run asynchronous $.getJSON in series.$.getJSON returns the $.Deferred object, so I didn't test it, but if you do the following excerpt, it will be serialized and the problem will be solved.In addition, the processing will be slow because it will be in series.

//Defining Variable j
varj = 0;

// **Add**Define variables to hold Deferred
vardfrd;

// Add for minutes
for(vari=0;i<264;i++){

    // Each variable definition;
    ...

    if(!dfrd){
        dfrd=(function(){
            vard = new$.Deferred();
            d.resolve();
            return.promise();
        })();
    }

    // **Change the point of issue as follows**
    dfrd.then(
        dfrd = $.getJSON(jsinfo,
            ( function(irank, iimg, iname, tab, target, j){
                return function(data){
                    if(data.items[0].summary!=""){
                        // Count of processing count
                        j = j+1;
                        // Processing details
                        vivid='<img src='+iimg+'" alt="empty" style="height:150px;" class="app-button" data-target="'+target+'">br>'+iname+';;
                        $(tab).append(vivid);
                    }
                };
            }) (irank, iimg, iname, tab, target, j)
        )
        .then(//alert is also not required to turn off the alert.
            alert(j);
        );
    );
}


2022-09-29 22:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.