2013-12-13 38 views
1

這個很簡單。在codeigniter我能有一個像Ajax調用:如何使用ajax調用codeigniter中的php函數?

$.ajax({ 
     type: "POST", 
     url: base_url + "index.php/mycontroller/myfunction" 
     //so in mycontroller.php^there is function myfunction() 
     data:{id : id}, 
     success:function(data){ 

     }; 
     }) 

由於class Mycontroller extends CI_Controller
所以,我該怎麼辦,在raw PHP如果我有posted.php,我怎麼能爲了這個文件延長我打電話給這樣的功能:

<?php 
     function test(){ 
      echo 'Hello World!'; 
     } 

我在想什麼是這樣的:

$.ajax({ 
     type: "POST", 
     url: "posted.php/test", //go to posted.php and call test function if possible 
     data:{id : id}, 
     success:function(data){ 

     }; 
     }) 

但這一個不工作。那麼有什麼幫助?

+0

你想打電話posted.php中的'test()'函數? (我通過你的編輯看到你在做什麼。) – CWSpear

+0

@CWSpear是的,我是爵士 – leonardeveloper

+1

那麼,你將不得不編寫自己的框架來解釋給定的URL並實例化控制器並調用該函數。除非下面的@Milanzor的方法對你的應用程序來說是'夠用'的。 – AmazingDreams

回答

6

你可以你的Ajax POST網址更改爲這樣的事情:

posted.php?call=test 

然後,在你的posted.php,檢查GET參數 '叫',並調用正確的函數:

switch($_GET['call']){ 

    case 'test': 
    test(); 
    break; 
} 


function test() { 
    echo "Hello, world!"; 
} 
+0

說明:您無法單獨通過HTTP請求調用函數。 PHP仍然需要確定你想要做什麼。這就是爲什麼它需要像這個答案這樣的處理程序指出你。所以要麼適應這個代碼,要麼實現你自己的。 – Daniel

+0

或者,你可以做$ _GET ['call']()。 –

+0

@adirohan是啊,如果你想讓你的用戶能夠調用所有可用的函數......哪個人不會想要。 – Daniel

1

CodeIgniter使用一些$_SERVER變量能夠爲您獲取這些信息。它實際上可以因環境而異,但它通常在$_SERVER['PATH_INFO'](某些環境甚至不支持此操作,並且CI有後備使用查詢參數)。

試試print_r($_SERVER);看看你是否有PATH_INFO變量。從那裏,CI可以使用字符串值來確定函數的名稱並調用它。

這裏有一個簡單的例子:

function test() 
{ 
    echo 'Test success!'; 
} 

$fn = trim(@$_SERVER['PATH_INFO'], '/'); 

if (function_exists($fn)) call_user_func($fn); 
else die ("No function: {$fn}"); 

附加信息:從關於它用於其路由CI源(application/config/config.php):

/* 
|-------------------------------------------------------------------------- 
| URI PROTOCOL 
|-------------------------------------------------------------------------- 
| 
| This item determines which server global should be used to retrieve the 
| URI string. The default setting of 'AUTO' works for most servers. 
| If your links do not seem to work, try one of the other delicious flavors: 
| 
| 'AUTO'   Default - auto detects 
| 'PATH_INFO'  Uses the PATH_INFO 
| 'QUERY_STRING' Uses the QUERY_STRING 
| 'REQUEST_URI'  Uses the REQUEST_URI 
| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO 
| 
*/ 
+0

在這裏看看先生。 http://codejaw.com/33jaq – leonardeveloper

+0

啊,你在Windows上。你在'/ posted.php/test'在那個轉儲嗎?如果PATH_INFO是空的,它根本不會顯示出來。實際上,你可能更喜歡@ Milanzor的解決方案,因爲它是解決AJAX內容問題的更好解決方案,但我試圖回答關於CI如何實現以及如何推出自己的具體問題。 – CWSpear