从入门jQuery的AJAX的形式后不确定的反应不确定、入门、反应、形式

由网友(涩涩先森)分享简介:$(document).ready(function() {$('#pricingEngine').change(function() {var query = $("#pricingEngine").serialize();$('#price').fadeOut(500).addClass('ajax-loading...
$(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的code。

Need to set #sku as value of a hidden form field (not sure if i am doing that correctly in the above jQuery code.

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

还需要通过 F_PRICE #price DIV

控制台在Chrome显示JSON响应为:

Console in Chrome shows the JSON response as:

[
 {
  "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"
 }
]

不过,我只得到在价格中未定义。什么是这里的原因?

Yet I only get 'undefined' in the price box. What is the reason here?

推荐答案

结构返回JSON是一个数组 [] 包含它是对象的一个​​元素 {} 你的目标。通过其数组索引访问 [0]

The structure returned as JSON is an array [] containing one element which is the object {} you are targeting. Access it via its array index [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()的第一个元素关闭阵列和使用,当你知道了:

You could also .shift() the first element off the array and use that as you have it:

// 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);
阅读全文

相关推荐

最新文章