Ajax响应未定义



我是一名编程新手。我试图插入var cPrice在我的前端HTML页面。然而,它是未定义的,我不明白为什么。

///////////// Display Pop-up finciton //////////////////
//Start//
$('#button1').on('click', function() {
// Show the popup
$('#openPopup').show();
// Get the symbol and name and show it in the popup
const symbolID = document.getElementById("symbolSearch").value.toUpperCase();
document.getElementById("currentSymbol").innerHTML = symbolID;

$.get("http://localhost:5000/placeOrder", function(err, price) {
console.log(price.currentPrice);
var cPrice = price.currentPrice // On the server-side it prints the correct value.
console.log(cPrice) // However, here the front-end value is undefined.
if (err) { console.log(err) } else {
document.getElementById("currPrice").innerHTML = cPrice
}
});

// Execute the function for retrieving the price
//userAction();

阅读docs: jQuery.get()获取success函数回调:
第一个参数是PlainObjectdata

jQuery.get( url [, data ] [, success ] [, dataType ] )
成功fn
类型:Function(data, textStatus, jqXHR)
请求成功时执行的回调函数。如果提供了dataType,则为必需,但您可以使用null或jQuery。Noop作为占位符

还有一个

弃用注意:
jqXHR.success()、jqXHR.error()和jqXHR.complete()回调方法从jQuery 3.0起被删除. 您可以使用jqXHR.done()、jqXHR.fail()和jqXHR.always()来代替。

因此,您最好使用更具可读性的代码.done().fail():

$.get("http://localhost:5000/placeOrder")
.done((data) => {
console.log(data);
console.log(data.currentPrice);
})
.fail((jqXHR, textStatus, errorThrown) => {
console.log(jqXHR);
}); 

最新更新