【问题标题】:Ajax response is undefinedAjax 响应未定义
【发布时间】:2021-10-28 15:19:48
【问题描述】:

我是新手编码员。我正在尝试在我的前端 HTML 页面中插入 var cPrice。但是,它是未定义的,我不知道为什么。

///////////// 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();

【问题讨论】:

  • 你能用 curl 或 postman 得到结果吗?
  • 是的,结果是148.6
  • 您的代码是否显示任何错误?
  • 没有。我删除了 .currentPrice,现在它显示“成功”而不是未定义。
  • 你的结果是错误的

标签: jquery node.js express


【解决方案1】:

阅读文档:jQuery.get() 获取 success 函数回调:
第一个参数是 PlainObject data

jQuery.get( url [, data ] [, success ] [, dataType ] )
fn 成功
类型:函数(数据,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);
  }); 

【讨论】:

    猜你喜欢
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 2021-06-21
    相关资源
    最近更新 更多