2013-03-30 21 views
1

我是CodeIgniter中的新成員。我想提出一個項目中,我使視圖中的JavaScript函數在此我定義一個變量..它看起來像這樣從code函數傳遞變量到codeigniter中的控制器方法

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在控制器功能中,我該怎麼做?

+0

如果你在'VIEW'文件中做javascript的話,會更好。 – egig

+0

@Charlie:這個javascript是可見的。 。 – Jay

+0

你不能在php中訪問javascript變量。簡單的原因是Javascript是客戶端,而PHP是在服務器上。 –

回答

0

只是爲了確保我理解你,你正試圖從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

現在:

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

方法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); 
相關問題