简体   繁体   English

调用函数时,在函数内发送ajax请求被延迟

[英]Sending ajax request within function is delayed when calling the function

Trying to get data from JSON when a button is pressed and for some reason I'm getting an error the first time the button is pressed and then if you hit it again I get the popup but with the id that was pressed the first time. 尝试在按下按钮时从JSON获取数据,由于某种原因,第一次按下该按钮时出现错误,然后如果再次单击它,我会弹出但带有第一次按下的ID。 i understand what it is doing but I don't know why. 我知道它在做什么,但我不知道为什么。

Data: 数据:

 id: 1, price: 5.00;
 id: 2, price: 9.30;

Script: 脚本:

function updateStock(id){

$.ajax({
    url: 'json.watching.php?id=' + id,
    dataType: 'json',
    cache: false,
    success: function(data) {
        price = data.price;
    }
});

    $('#dialog-popup').html("<div align='center'>id: " + id + ". Price: " + price + "</div>");
    $("#dialog-popup").dialog("open");
}

Buttons: 纽扣:

<button onclick="updateStock(1)" style="button">Button 1</button>
<button onclick="updateStock(2)" style="button">Button 2</button>

The first time the button is pressed I get the Uncaught ReferenceError: price is not defined but if I press it again I get the data but from the id of the button press before it. 第一次按下按钮时,我得到了Uncaught ReferenceError:价格未定义,但是如果再次按下它,则会得到数据,但从按钮的ID之前可以得到。 So if load the page and press the first button I get the error, if I press the same button I get the popup with the correct price, but I if I hit the second button my popup responds with "id: 2. Price: 5.00". 因此,如果加载页面并按第一个按钮,则会收到错误消息;如果按相同的按钮,则会显示具有正确价格的弹出窗口,但是如果我单击第二个按钮,我的弹出窗口将显示“ id:2。价格:5.00” ”。 The id is correct but the ajax data is from the previous button press and doesn't update the variables. id是正确的,但是ajax数据来自上一次按下按钮,并且不会更新变量。

Ajax is asyncbronous, so you are reading the value before it si set. Ajax是异步的,因此您要在设置之前读取值。 Move the dialog call to inside the success call. 将对话框调用移至成功调用内部。

function updateStock(id){
  $.ajax({
    url: 'json.watching.php?id=' + id,
    dataType: 'json',
    cache: false,
    success: function(data) {
        price = data.price;
        $('#dialog-popup').html("<div align='center'>id: " + id + ". Price: " + price + "</div>");
        $("#dialog-popup").dialog("open");
    }
  });
}

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

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