【问题标题】:Getting undefined response from jQuery AJAX form post从 jQuery AJAX 表单帖子中获取未定义的响应
【发布时间】:2012-11-03 20:49:59
【问题描述】:
$(document).ready(function() {
    $('#pricingEngine').change(function() {
         var query = $("#pricingEngine").serialize();
         $('#price').fadeOut(500).addClass('ajax-loading');
         $.ajax({
             type: "POST",
             url: "index.php/welcome/PricingEngine",
             data: query,
             dataType: 'json',
             success: function(data)
             {
               $('#price').removeClass('ajax-loading').html('$' + data.F_PRICE).fadeIn(500);
               $('#sku').attr('value') = (data.businesscards_id);
             }
         });
    return false;
   });
});

需要将#sku 设置为隐藏表单字段的值(不确定我在上面的 jQuery 代码中是否正确。

<input type="hidden" name="sku" id="sku" value="*/PUT VAR VALUE HERE/*" />

还需要将F_PRICE传递给#price div

Chrome 中的控制台将 JSON 响应显示为:

[
 {
  "businesscards_id":"12",
  "X_SIZE":"1.75x3",
  "X_PAPER":"14ptGlossCoatedCoverwithUV(C2S)",
  "X_COLOR":"1002",
  "X_QTY":"250",
  "O_RC":"NO",
  "F_PRICE":"12490",
  "UPS_GROUND":"12000",
  "UPS_TWODAY":"24000",
  "UPS_OVERNIGHT":"36000"
 }
]

但我只在价格框中看到“未定义”。这是什么原因?

【问题讨论】:

  • 只需在 ajax 响应/成功方法中使用 shift(),n 代码就可以正常工作。 :)

标签: php javascript jquery ajax


【解决方案1】:

以 JSON 形式返回的结构是一个数组 [],其中包含一个元素,即您要定位的对象 {}。通过其数组索引[0]访问它

// Access the array-wrapped object via its [0] index:
$('#price').removeClass('ajax-loading').html('$' + data[0].F_PRICE).fadeIn(500);
// Likewise here, and set the value with .val()
$('#sku').val(data[0].businesscards_id);

您也可以.shift() 数组中的第一个元素并使用它:

// Pull the first element off the array, into the same variable
// WARNING: Use a different variable if the array has multiple elements you need to loop over later.
// You *don't* want to do it this way if the array contains multiple objects.
data = data.shift();
$('#price').removeClass('ajax-loading').html('$' + data.F_PRICE).fadeIn(500);
$('#sku').val(data.businesscards_id);

【讨论】:

  • 是的,刚刚意识到 data = data[0];但是为什么我需要它呢?
  • @fabio 你是什么意思你为什么需要它?您的 AJAX 调用返回一个数组。如果您希望它只返回单个对象,则需要在服务器端对其进行修改。
  • 好吧,我明白为什么我现在必须这样做了。我不知道 JSON 格式。然而,代码部分工作。 $('#sku').val(data[0].businesscards_id); 没有设置隐藏字段输入的值。有什么想法吗?谢谢您的帮助! :)
  • @fabio 将值设置为什么? .val() 从 1.0 开始就在 jQuery 中。你用的是超老版本吗?
  • 没有最新版本的google cdn——它没有设置任何东西,也没有控制台错误:这里来自源&lt;input type="hidden" name="sku" id="sku" value="" /&gt;
【解决方案2】:

这是正确的方式(最好的)

$('#sku').val(data.businesscards_id);

如果你坚持使用 attr,这应该可行

$('#sku').attr('value', data.businesscards_id);

【讨论】:

    猜你喜欢
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 2019-01-20
    • 2010-10-24
    • 1970-01-01
    相关资源
    最近更新 更多