使用 jquery $.ajax 调用 PHP 函数 [英] using jquery $.ajax to call a PHP function
问题描述
这可能是一个简单的答案,但我使用 jQuery 的 $.ajax 来调用 PHP 脚本.我想要做的基本上是将该 PHP 脚本放在一个函数中并从 javascript 调用该 PHP 函数.
This may be a simple answer, but I'm using jQuery's $.ajax to call a PHP script. What I want to do is basically put that PHP script inside a function and call the PHP function from javascript.
<?php
if(isset($_POST['something'] {
//do something
}
?>
到这里
<?php
function test() {
if(isset($_POST['something'] {
//do something.
}
}
?>
我将如何在 javascript 中调用该函数?现在我只是使用 $.ajax 和列出的 PHP 文件.
How would i call that function in javascript? Right now i'm just using $.ajax with the PHP file listed.
推荐答案
使用 $.ajax
调用服务器上下文(或 URL,或其他)来调用特定的操作".你想要的是这样的:
Use $.ajax
to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
在服务器端,应该读取 action
POST 参数,并且对应的值应该指向要调用的方法,例如:
On the server side, the action
POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : test();break;
case 'blah' : blah();break;
// ...etc...
}
}
我相信这是命令模式的简单化身.
I believe that's a simple incarnation of the Command pattern.
这篇关于使用 jquery $.ajax 调用 PHP 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!