如何在 PHP 中使用 AJAX 返回变量?我目前正在控制器中使用 echo 来显示价格dropdown .change
in a div
称为价格。
但是我有一个隐藏字段,我需要在更改时将行 ID 返回到该隐藏字段。如何在 jQuery 中分配返回变量,以便我可以在隐藏字段中回显它?
jQuery
$(document).ready(function() {
$('#pricingEngine').change(function() {
var query = $("#pricingEngine").serialize();
$('#price').fadeOut(500).addClass('ajax-loading');
$.ajax({
type: "POST",
url: "store/PricingEngine",
data: query,
success: function(data)
{
$('#price').removeClass('ajax-loading').html('$' + data).fadeIn(500);
}
});
return false;
});
});
控制器
function PricingEngine()
{
//print_r($_POST);
$this->load->model('M_Pricing');
$post_options = array(
'X_SIZE' => $this->input->post('X_SIZE'),
'X_PAPER' => $this->input->post('X_PAPER'),
'X_COLOR' => $this->input->post('X_COLOR'),
'X_QTY' => $this->input->post('X_QTY'),
'O_RC' => $this->input->post('O_RC')
);
$data = $this->M_Pricing->ajax_price_engine($post_options);
foreach($data as $pData) {
echo number_format($pData->F_PRICE / 1000,2);
return $ProductById = $pData->businesscards_id;
}
}
View
这是我的隐藏字段,我想在每次表单更改时将 VAR 传递给它。
” />
谢谢您的帮助!
嗯.. 一种选择是返回 JSON 对象。要在 PHP 中创建 JSON 对象,您需要从一个值数组开始,然后执行json_encode($arr)
。这将返回一个 JSON 字符串。
$arr = array(
'stack'=>'overflow',
'key'=>'value'
);
echo json_encode($arr);
{"stack":"overflow","key":"value"}
现在在你的 jQuery 中,你必须告诉你的$.ajax
调用您期望一些 JSON 返回值,因此您指定另一个参数 -dataType : 'json'
。现在你的返回值在success
函数将是一个普通的 JavaScript 对象。
$.ajax({
type: "POST",
url: "...",
data: query,
dataType: 'json',
success: function(data){
console.log(data.stack); // overflow
console.log(data.key); // value
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)