如何成功AJAX / jQuery的POST返回PHP变量 [英] How to return PHP variables on success AJAX/jQuery POST

查看:199
本文介绍了如何成功AJAX / jQuery的POST返回PHP变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用AJAX在PHP中返回一个变量?我目前正在使用的回声在我的控制器上显示的 DIV 叫价下拉.change 价格。

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返回到上的变化。我该如何分配收益VAR 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_en code($ 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的返回值,所以你指定的另一个参数 - 数据类型:JSON。现在在成功的返回值功能将是一个普通的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆