如何在成功 AJAX/jQuery POST 时返回 PHP 变量 [英] How to return PHP variables on success AJAX/jQuery POST
问题描述
如何在 PHP 中使用 AJAX 返回变量?我目前在我的控制器中使用 echo 在 dropdown .change
上显示价格,在 div
中称为 price.
How do I use AJAX to return a variable in PHP? I am currently using echo in my controller to display a price on dropdown .change
in a div
called price.
但是我有一个隐藏字段,我需要在更改时将行 ID 返回到该字段.我如何在 jQuery 中分配返回变量,以便我可以在我的隐藏字段中回显它?
However I have a hidden field which I need to return the row id to on change. How do I assign the return var in jQuery so that I can echo it in my hidden field?
$(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;
}
}
查看
这是我的隐藏字段,我想在每次更改表单时将 VAR 传递给."/>
View
Here is my hidden field I want to pass the VAR to every-time the form is changed. " />
感谢您的帮助!
推荐答案
嗯.. 一种选择是返回一个 JSON 对象.要在 PHP 中创建 JSON 对象,您需要从一组值开始,然后执行 json_encode($arr)
.这将返回一个 JSON 字符串.
Well.. One option would be to return a JSON object. To create a JSON object in PHP, you start with an array of values and you execute json_encode($arr)
. This will return a JSON string.
$arr = array(
'stack'=>'overflow',
'key'=>'value'
);
echo json_encode($arr);
{"stack":"overflow","key":"value"}
现在在您的 jQuery 中,您必须告诉 $.ajax
调用您需要一些 JSON 返回值,因此您指定另一个参数 - dataType : 'json'代码>.现在
success
函数中的返回值将是一个普通的 JavaScript 对象.
Now in your jQuery, you'll have to tell your $.ajax
call that you are expecting some JSON return values, so you specify another parameter - dataType : 'json'
. Now your returned values in the success
function will be a normal JavaScript object.
$.ajax({
type: "POST",
url: "...",
data: query,
dataType: 'json',
success: function(data){
console.log(data.stack); // overflow
console.log(data.key); // value
}
});
这篇关于如何在成功 AJAX/jQuery POST 时返回 PHP 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!