简体   繁体   English

用AJAX调用PHP函数吗?

[英]Call PHP function with AJAX?

I know I can do this: 我知道我可以这样做:

//Jquery
$.ajax({type: 'POST', data : {'action' : 'foo'}});

//PHP
if(isset($_POST['action']) && $_POST['action'] == 'foo')
{
    function foo()
    {
        //yeah
    }
}

But.. In a project I'm working on with a friend, he has set up the controllers to be able to have specific functions called using custom actions. 但是..在我和朋友一起工作的项目中,他设置了控制器,以便能够使用自定义操作调用特定功能。 For instance, say my view is using the controller of thing.php. 例如,假设我的视图是使用thing.php的控制器。 From my Javascript I can just AJAX to a url like this: 从我的Java语言,我可以将AJAX转换为这样的网址:

'url' : 'thing'

So in this case, foo() would get called without a need for any ifs or switches (as far as I know) 所以在这种情况下,foo()将被调用而不需要任何ifs或开关(据我所知)

To me, this is great and ideal but I'm not sure how it was set up. 对我而言,这是伟大而理想的,但我不确定它是如何设置的。 He isn't around for the holidays to ask so I'm asking you guys. 他不在假期,所以我问你们。

Do you know how this is achieved? 你知道这是如何实现的吗? We are using a pretty typical MVC architecture. 我们使用的是非常典型的MVC架构。 Sorry I am a PHP novice. 对不起我是PHP新手。 Thanks! 谢谢!

It looks like your friend is using .htaccess to rewrite URLS to add .php , perhaps with 看起来你的朋友正在使用.htaccess来重写URL以添加.php ,也许是

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

Now if you call a URL like /thing it will actually call the file /thing.php on your server and execute it. 现在,如果您调用/thing之类的URL,它将实际上调用服务器上的/thing.php文件并执行它。 Or in your case if your url is just thing without the starting / it will call the thing.php in the same folder your current page is in. 或者在你的情况下,如果你的网址只是没有开始的thing /它将调用当前页面所在的同一文件夹中的thing.php

Or perhaps he is rewriting everything to the controller and then adding the variable as command. 或者他可能正在重写控制器的所有内容,然后将变量添加为命令。 Something like 就像是

RewriteRule ^(.*)$ controller.php?action=$1

Anyway, check your/his .htaccess file for clues 无论如何,请检查您/他的.htaccess文件以获取线索

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM