简体   繁体   English

将变量从javascript函数传递到codeigniter中的控制器方法

[英]pass variable from javascript function to controller method in codeigniter

I'm new in CodeIgniter. 我是CodeIgniter的新手。 I am making a project in which I make a javascript function in view an in this I define a variable .. it looks like this 我正在制作一个项目,在该项目中,我会在其中创建一个javascript函数,并在其中定义一个变量..它看起来像这样

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

my controller function contains 我的控制器功能包含

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();
 }

I want to access the variable $rowCount in controller function, how can I do that? 我想访问控制器函数中的变量$rowCount ,该怎么办?

Just to make sure I understand you, You are trying to pass a variable from javascript to CodeIgniter's controller function, right? 为了确保我理解您,您正在尝试将javascript中的变量传递给CodeIgniter的控制器函数,对吗?

If that's your case(hopefully it is), then you can use AJAX, or craft an anchor link. 如果您的情况如此(希望如此),则可以使用AJAX或制作锚链接。

First of all, you're going to use the URI class , specifically the segment() function. 首先,您将使用URI类 ,特别是segment()函数。

Let's assume this is your controller: 假设这是您的控制器:

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();
    }
}

Now with javascript you can either craft an anchor tag, or use AJAX: 现在,使用javascript可以制作锚标记或使用AJAX:

Method 1: By crafting an anchor tag: 方法1:通过制作锚标记:

<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>

Method 2: By using AJAX: 方法2:通过使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM