本文介绍了从入门jQuery的AJAX的形式后不确定的反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$(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);
这篇关于从入门jQuery的AJAX的形式后不确定的反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!