php - 将变量从 javascript 函数传递到 codeigniter 中的 Controller 方法

标签 php javascript codeigniter codeigniter-2

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

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

我的 Controller 功能包含

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

我想访问 Controller 函数中的变量$rowCount,我该怎么做?

最佳答案

只是为了确保我理解您的意思,您正在尝试将变量从 javascript 传递到 CodeIgniter 的 Controller 函数,对吗?

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

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

假设这是您的 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();
    }
}

现在,您可以使用 javascript 制作 anchor 标记,或使用 AJAX:

方法 1:通过制作 anchor 标记:

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

方法 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);

关于php - 将变量从 javascript 函数传递到 codeigniter 中的 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15716265/

相关文章:

php - Facebook PHP SDK - 发布到 Facebook 页面但已创建帖子时出现错误

php - 空白页且无法下载 PHPExcel

php - 从 MySQL 检索 mysqli_real_escape_string

javascript - HTML overflow-x 设置焦点

javascript - 模拟链接单击而不与 jquery 中的用户交互?

php - 无法在CodeIgniter中调用 session 变量

PHP + MS SQL Server 字符编码

php - 使用旧版 codeigniter 站点设置魔术引号 PHP 错误

forms - 在Codeigniter中扩展表单验证

javascript - ChartJS : Position labels at end of doughnut segment