【问题标题】:How to call a codeigniter helper function using JQuery AJAX?如何使用 JQuery AJAX 调用 codeigniter 辅助函数?
【发布时间】:2015-05-08 22:57:54
【问题描述】:

我在 codeigniter 的辅助函数中定义了一个函数,当 val 和货币 id 传递给它时,它返回格式化的价格。

if(!function_exists('format_price')){
function format_price($val,$curency_id=NULL){
    $CI =& get_instance();
    $CI->load->model('currency_model');
    if ($curency_id) {
        $Result=$CI->currency_model->getcurrency($curency_id);
        $dec_place=round($Result['decimal_place']);
        $value=number_format((float)$val,$dec_place,'.',',');
        return $Result['symbol_left'].$value ." ".$Result['symbol_right'];
    }
    else{
        $Result=$CI->currency_model->getDefaultCurrency();
        $dec_place=round($Result['decimal_place']);
        $value=number_format((float)$val,$dec_place,'.',',');
        return $Result['symbol_left'].$value ." ".$Result['symbol_right'];
    }
   }
}

我需要的是通过 ajax 在 javascript 代码中调用这个函数。 没有控制器这可能吗,还是我必须制作一个控制器?

【问题讨论】:

  • 你必须调用一个控制器来调用你的助手并返回结果
  • 我试过了,但是没有显示返回值。
  • 有什么错误吗?首先测试你的控制器,确保它返回一些东西。如果是,请检查您的 ajax 调用。
  • 它返回但未定义

标签: javascript php jquery ajax codeigniter


【解决方案1】:

您需要通过控制器发出请求,然后通过该控制器调用该函数,例如:

$("#id").change(function()
{       
 $.ajax({
     type: "POST",
     url: base_url + "controller_name/your_function", 
     data: {val: $("#your_val").val(),currency_id: $("#your_cur").val()},
     dataType: "JSON",  
     cache:false,
     success: 
          function(data){
            $("#your_elem").val(data.price);
      }
});

然后在你的控制器上:

public function yourfunction()
{
   $data = $this->input->post();
   $price = format_price($data['val'],$data['currency_id']);
   echo json_encode(array('price' => $price));
}

【讨论】:

  • 当我返回数据success:function(){ return data;}它给出未定义
  • 你应该使用data.price
【解决方案2】:

不要像这样使用ajax尝试......

<script type="text/javascript">
  $(document).ready(function(){
    (function(){
      <?php if(helper_function($variable)) { ?>
          now your jquery script..........
      <?php } ?>
    });
  });
</script>

根据需要自定义上面的代码......

【讨论】:

  • 感谢重播,但你没有得到我。我想调用辅助函数。
  • 据我了解,您想在 jquery 中使用辅助函数..so &lt;?php if(helper_function($variable)) { ?&gt; 将调用您的辅助函数...
  • 我的变量是var currency_id,and and var total_amout,它不能像那样传递,因为这些是jquery变量。
  • 你可以使用 php 和/或 jquery 来获取 total_amount 和 currency_id ....在调用辅助方法之前......你试图打破 mvc 结构......所以你必须做这样的事情
猜你喜欢
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
  • 2015-11-09
  • 2010-11-24
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多