For循环中Ajax调用的顺序和动态数

时间:2018-06-14 10:45:08

标签: javascript jquery



var data = [{start_date:20180601,end_date:20180701},{start_date:20180801,end_date:20180901},{start_date:20181001,end_date:20181101},{start_date:20181201,end_date:20190101}];
var requests = [];
for (var i = 0; i < data.length; i++) {
      (function(i, data) {
        requests.push(function() {
          jQuery.ajax({
            url: 'https://reqres.in/api/users?page=1',
            method: 'GET',
            success: function(result) {
              console.log(i); // 0
              requests[i].apply(undefined, []);
            }
          });
        });
        console.log(i); //counts up
      })(i, data);

    };

 requests[0].apply(undefined,[]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

我想知道,这段代码是怎么来的:

for (var i = 0; i < data.length; i++) {
  (function(i, data) {
    requests.push(function() {
      jQuery.ajax({
        url: wpApiSettings.root + 'superdooperendpoint/' + apikey + "/" + data[i].start_date + "/" + data[i].end_date,
        method: 'GET',
        beforeSend: function(xhr) {
          // Set nonce here
          xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
        },
        success: function(result) {
          success_callback({
            start_date: data[i].start_date,
            end_date: data[i].end_date,
            span: data[i].span,
            result: result
          });
          console.log(i); // 0
          requests[i].apply(undefined, []);
        }
      });
    });
    console.log(i); //counts up
  })(i, data);

};

当我在成功函数中执行第一个console.log()时,它总是0,而不是undefined,但是在成功函数之外,它会在迭代for循环中计数。如何才能让它在success函数中计算?

2 个答案:

答案 0 :(得分:1)

以下描绘了originalInputs

的更新值

并行通话

&#13;
&#13;
i
&#13;
var data = [{start_date:20180601,end_date:20180701},{start_date:20180801,end_date:20180901},{start_date:20181001,end_date:20181101},{start_date:20181201,end_date:20190101}];
var requests = [];
for (var i = 0; i < data.length; i++) {
  (function(i, data) {
    requests.push(function() {
      jQuery.ajax({
        url: 'https://reqres.in/api/users?page=1',
        method: 'GET',
        success: function(result) {
          console.log(i);
        }
      });
    });
  })(i, data);

};

for (var i = 0; i < requests.length; i++) {
  requests[i].apply(undefined, []);
}
&#13;
&#13;
&#13;

顺序通话

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
var data = [{start_date:20180601,end_date:20180701},{start_date:20180801,end_date:20180901},{start_date:20181001,end_date:20181101},{start_date:20181201,end_date:20190101}];
var requests = [];
for (var i = 0; i < data.length; i++) {
  (function(i, data) {
    requests.push(function() {
      jQuery.ajax({
        url: 'https://reqres.in/api/users?page=1',
        method: 'GET',
        success: function(result) {
          console.log(i);
          i++;
          if(i < requests.length) {
            requests[i].apply(undefined, []);          
          }
        }
      });
    });
  })(i, data);

};

requests[0].apply(undefined, []);
&#13;
&#13;
&#13;

解释 - 迭代函数时,对于<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>数组中的每个函数,requests的值就像参数一样被传递/存储。当您从外部调用i时,在函数完成时,将绘制requests[0]的存储值,即0。然后,再次触发存储在i的函数,即最终创建无限循环。为了绘制适当的值,循环遍历index = 0数组并逐个调用单个函数以查看正在记录的i的适当值。

答案 1 :(得分:0)

您需要将i分配给嵌套函数的其他局部变量,并将let i = 0; for (; i < 100; i++) { ((n) => new Promise( (res, rej) => setTimeout(res, 100) ).then(() => console.log(i,n)) )(i); } 的定义放在块之外;

class Window(tk.Tk):

x = datetime.today()
y = x.replace(x.second+30 , hour=0, minute=0, second=0, microsecond=0)
delta_t = y - x

secs = delta_t.seconds + 1
sched = BlockingScheduler()
root = tk.Tk()


def reading_APIfile(self):
    # getting current time.
    print("here is what is in " )
    current_time = strftime("%H:%M:%S", gmtime())
    # open and read from json file
    # threading.Timer(10, self.reading_APIfile()).start()


    with open('JSONresponse.json') as a:
        json_dict = json.load(a)
       # print(current_time)
        self.locationDescription = json_dict['locationDescription']
        self.location = json_dict['name']
        for obj in json_dict['sessions']:
            for key in obj:
                if obj['stringStartTime'] <= current_time and obj['stringEndTime'] >= current_time:
                    self.qrCodeToken = obj['token']
                    self.startTime = obj['stringStartTime']
                    self.endTime = obj['stringEndTime']
                elif obj['stringEndTime'] <= current_time:
                    self.qrCodeToken = obj['token']
                    self.startTime = obj['stringStartTime']
                    self.endTime = obj['stringEndTime']
                for x in obj['courses']:
                    for key1 in x:
                        self.subject = x['subjectCode'] + " " + x['subject']
                        self.Name = x['className']


def __init__(self):
    # self.gettingAPI()
    self.reading_APIfile()
    tk.Tk.__init__(self)
    self.title("ODUATTAND")
    self.geometry('{}x{}'.format(660, 350))
    self.attributes('-zoomed', True)  # This just maximizes it so we can see the window. It's nothing to do with fullscreen.
    #self.frame = Frame(self.tk)
    #self.frame.pack()
    self.state = False
    self.bind("<F11>", self.toggle_fullscreen)
    self.bind("<Escape>", self.end_fullscreen)

    #Generat Qr code.

    big_code = pyqrcode.create(self.qrCodeToken, error='L')
    #print(self.qrcodetoken)
    big_code.png('code.png', scale=6, module_color=[0, 0, 0, 128], background=[0xff, 0xff, 0xff])

    # Main container
   # topleft = Frame(self, bg='white')
    btm_left = Frame(self, bg='white')
    top_right = Frame(self, bg='white')
    btm_right = Frame(self, bg='white')

    self.grid_rowconfigure(1, weight=1)
    self.grid_columnconfigure(0,weight=1)

    # old frame setting
    for r in range(6):
        self.grid_rowconfigure(r, weight=1)
    for c in range(5):
        self.grid_columnconfigure(c, weight=1)

    # x= self.reading_APIfile.subject
    # print ("here is X" + x)
    #topleft.grid(row = 0, column = 0, rowspan = 4, columnspan = 4, sticky = W+E+N+S)
    btm_left.grid(row = 0, column = 0, rowspan = 6, columnspan = 6, sticky = W+E+N+S)
    top_right.grid(row = 0, column = 3, rowspan = 4, columnspan = 3,padx=0, sticky = W+E+N+S)
    btm_right.grid(row = 2, column = 3, rowspan = 4, columnspan = 3, sticky = W+E+N+S)
    btm_right.grid(row=2, column=3, rowspan=4, columnspan=3, sticky=W + E + N + S)

    self.label1 = tk.Label(top_right, text= self.subject+ ": "+ self.Name +"\n" + self.location +"\n "+ self.startTime+ " "+ self.endTime)
    self.label1.place(x=190,y=45,anchor="center")
    self.label1.config(width=300, font=("Arial", 12), bg="white")

    # reading the card
    self.code = ''

    self.label = tk.Label(btm_right, text="PLease swipe your card")
    self.label.place(x=150, y=155, anchor="center")
    self.label.config(width=200, font=("Arial", 12), bg="white",padx=0)


    #if self.code !="":

    self.canvas = Canvas(btm_right, width=250, height=200, highlightthickn=0)
    self.canvas.place(x=120,y=40, anchor="center")
    tk_img = Image.open('check.png')
    check_img1=tk_img.resize((150,130), Image.ANTIALIAS)
    check_img2=ImageTk.PhotoImage(check_img1)
    panel = tk.Label(btm_right, image=check_img2)
    panel.image = check_img2
    self.x = self.canvas.create_image( 155, 125, image=check_img2)
    self.canvas.itemconfigure(self.x, state=tk.HIDDEN)
    self.canvas.configure(background='white')
    # self.label1.grid(row=2, column=2)


    self.bind('<Key>', self.get_key)

    #insert QR code
    Qrimage = Image.open('code.png')
    Qrimage1 = Qrimage.resize((400, 400), Image.ANTIALIAS)
    Qrimage2 = ImageTk.PhotoImage(Qrimage1)
    # img=img.subsample(2,2)
    panel = tk.Label(btm_left, image=Qrimage2)
    panel.place(x=200, y=175, anchor="center")
    # panel.grid(row=0, column=1, sticky="nw")
    panel.image = Qrimage2

    # insert a Logo
    path = "/home/mohamedshaaban/PycharmProjects/untitled1/986.gif"

    image = Image.open('986.gif')
    image1 = image.resize((100, 50), Image.ANTIALIAS)
    image2 = ImageTk.PhotoImage(image1)
    # img=img.subsample(2,2)
    panel = tk.Label(btm_right, image=image2)
    panel.place(x=160, y=200, anchor="center" )
    panel.config(highlightthickness=0)
    # panel.grid(row=0, column=1, sticky="nw")
    panel.image = image2

    top_right.grid_rowconfigure(0, weight=1)
    top_right.grid_columnconfigure(1, weight=1)
    # self.th = threading.Timer(5.0,self.callinginit)
    print("here is what is 222 ")
    # self.callinginit()

    def callinginit(self):
        # self.__init__()
        self.reading_APIfile()
        print("it is working")
        # self.after(150000,self.callinginit())