gpt4 book ai didi

javascript - Javascript 中同步函数内的异步函数

转载 作者:行者123 更新时间:2023-12-03 02:33:24 25 4
gpt4 key购买 nike

在通过代码加载一些 HTML 时,我想从服务器获取一些数据。因此,我从同步函数开始,并在其中调用 POST。

我创建了一个示例

$(document).ready(function() {

for (var i = 1; i < 6; i++) {
var div = $("<div></div>");

var price = 0;

/* get the price from the server by passing the object id

$.ajax({
type: 'POST',
url: '/getPrice',
contentType: 'application/json',
data: JSON.stringify({
id: i
})
}).done(function(response) {
price = response.price;
});

*/

div.html("id " + i + " price " + price);

$("#container").append(div);
}

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
</div>

运行代码时,价格始终为 0 。我知道 AJAX 调用是异步的,但如何修复代码?

最佳答案

将代码放入done中,就像

$.ajax({
type: 'POST',
url: '/getPrice',
contentType: 'application/json',
data: JSON.stringify({
id: i
})
}).done(function(response) {
price = response.price;
div.html("id " + i + " price " + price);
$("#container").append(div);
});

关于javascript - Javascript 中同步函数内的异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48639943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com