如何使用ajax调用类似于codeigniter中的php函数


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

由于CCD_ 2
那么,如果我有posted.php,我如何在raw 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
|
*/