[英]How to call a php function like in codeigniter using ajax?
這很簡單。 在codeigniter
我可以像這樣進行ajax調用:
$.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
。
因此,如果我已經發布了posted.php
,該如何在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){
};
})
但這是行不通的。 有什么幫助嗎?
您可以將ajax POST URL更改為以下內容:
posted.php?call=test
然后,在您的posted.php中,檢查GET參數“ call”並調用正確的函數:
switch($_GET['call']){
case 'test':
test();
break;
}
function test() {
echo "Hello, world!";
}
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
|
*/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.