【问题标题】:pass variable from javascript function to controller method in codeigniter将变量从javascript函数传递到codeigniter中的控制器方法
【发布时间】:2013-03-30 07:43:23
【问题描述】:

我是 CodeIgniter 的新手。我正在制作一个项目,其中我在视图中创建了一个 javascript 函数,并在其中定义了一个变量.. 它看起来像这样

var $rowCount=0;
function invest() {
  $rowCount=$('#ulinvestment').find('.rowInvestment').length;
}

我的控制器功能包含

function input(parameter //i want to pass $rowcount value here ){
$this->load->helper('form');
$this->load->helper('html');
$this->load->model('mod_user');
$this->mod_user->insertdata();
 }

我想在控制器函数中访问变量$rowCount,我该怎么做?

【问题讨论】:

  • 最好在 'VIEW' 文件中做 javascript 的东西。
  • @Charlie:这个 javascript 正在查看中。 .
  • 您无法访问 php 中的 javascript 变量。原因很简单,Javascript 是客户端,而 PHP 是服务器端。
  • @SureshKamrushi :我实际上想在我的 javascript 代码中调用控制器函数(例如输入(参数))
  • $.post('codeigniter/controller/input',{ param1: "param2", param2: "param2" } function(data) { $('.result').html(data) ;});

标签: php javascript codeigniter codeigniter-2


【解决方案1】:

只是为了确保我理解你,你试图将一个变量从 javascript 传递给 CodeIgniter 的控制器函数,对吧?

如果这是您的情况(希望是),那么您可以使用 AJAX,或制作锚链接。

首先,您将使用URI class,特别是segment() 函数。

假设这是您的控制器:

class MyController extends CI_Controller
{
    function input(){
    $parameter = $this->uri->segment(3);//assuming this function is accessable through MyController/input

    $this->load->helper('form');
    $this->load->helper('html');
    $this->load->model('mod_user');
    $this->mod_user->insertdata();
    }
}

现在使用 javascript,您可以制作锚标记,也可以使用 AJAX:

方法一:通过制作锚标签:

<a href="" id="anchortag">Click me to send some data to MyController/input</a>


<script>

var $rowCount=0;
function invest() {
  $rowCount=$('#ulinvestment').find('.rowInvestment').length;
}
$('#anchortag').prop('href', "localhost/index.php/MyController/input/"+$rowCount);
</script>

方法二:使用AJAX:

var $rowCount=0;
function invest() {
  $rowCount=$('#ulinvestment').find('.rowInvestment').length;
}
//Send AJAX get request(you can send post requests too)
$.get('localhost/index.php/MyController/input/'+$rowCount);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 2017-05-28
    • 2015-09-10
    • 1970-01-01
    相关资源
    最近更新 更多