2
$(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"
 }
]

然而,我只在价格框中得到“未定义”。这是什么原因?

4

2 回答 2

2

返回为 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);
于 2012-11-03T20:54:01.093 回答
0

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

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

如果您坚持使用 attr,这应该可以

$('#sku').attr('value', data.businesscards_id);
于 2012-11-03T20:53:51.947 回答