使用 jquery $.ajax 调用 PHP 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2269307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using jquery $.ajax to call a PHP function
提问by Catfish
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.
这可能是一个简单的答案,但我使用 jQuery 的 $.ajax 来调用 PHP 脚本。我想要做的基本上是将该 PHP 脚本放在一个函数中并从 javascript 调用 PHP 函数。
<?php
if(isset($_POST['something'] {
//do something
}
?>
to this
对此
<?php
function test() {
if(isset($_POST['something'] {
//do something.
}
}
?>
How would i call that function in javascript? Right now i'm just using $.ajax with the PHP file listed.
我将如何在 javascript 中调用该函数?现在我只是使用 $.ajax 和列出的 PHP 文件。
回答by karim79
Use $.ajaxto call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:
使用$.ajax调用服务器上下文(或URL,或其他)来调用特定的“动作”。你想要的是这样的:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
On the server side, the actionPOST parameter should be read and the corresponding value should point to the method to invoke, e.g.:
在服务器端,action应该读取 POST 参数并且对应的值应该指向要调用的方法,例如:
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.
我相信这是命令模式的一个简单化身。
回答by Xaxis
I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php
我开发了一个 jQuery 插件,它允许你调用任何核心 PHP 函数甚至用户定义的 PHP 函数作为插件的方法:jquery.php
After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.
在我们的文档头部包含 jquery 和 jquery.php 并将 request_handler.php 放在我们的服务器上之后,我们将开始以下面描述的方式使用插件。
For ease of use reference the function in a simple manner:
为了便于使用,请以简单的方式引用该函数:
var P = $.fn.php;
Then initialize the plugin:
然后初始化插件:
P('init',
{
// The path to our function request handler is absolutely required
'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',
// Synchronous requests are required for method chaining functionality
'async': false,
// List any user defined functions in the manner prescribed here
// There must be user defined functions with these same names in your PHP
'userFunctions': {
languageFunctions: 'someFunc1 someFunc2'
}
});
And now some usage scenarios:
现在一些使用场景:
// Suspend callback mode so we don't work with the DOM
P.callback(false);
// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
Demonstrating PHP function chaining:
演示 PHP 函数链:
var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );
Demonstrating sending a JSON block of PHP pseudo-code:
演示发送 PHP 伪代码的 JSON 块:
var data1 =
P.block({
$str: "Let's use PHP's file_get_contents()!",
$opts:
[
{
http: {
method: "GET",
header: "Accept-language: en\r\n" +
"Cookie: foo=bar\r\n"
}
}
],
$context:
{
stream_context_create: ['$opts']
},
$contents:
{
file_get_contents: ['http://www.github.com/', false, '$context']
},
$html:
{
htmlentities: ['$contents']
}
}).data();
console.log( data1 );
The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.
后端配置提供了一个白名单,因此您可以限制可以调用哪些函数。插件还描述了其他一些使用 PHP 的模式。
回答by Felix Kling
I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC(JSON Remote Procedure Call).
我会坚持使用直接调用文件的正常方法,但是如果您真的想调用一个函数,请查看JSON-RPC(JSON 远程过程调用)。
You basically send a JSON string in a specific format to the server, e.g.
您基本上将特定格式的 JSON 字符串发送到服务器,例如
{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}
which includes the function to call and the parameters of that function.
其中包括要调用的函数和该函数的参数。
Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPCand e.g. the Zend JSON Serveras server implementation in PHP.
当然,服务器必须知道如何处理此类请求。
这是用于 JSON-RPC 的 jQuery 插件,例如Zend JSON 服务器作为 PHP 中的服务器实现。
This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.
对于小项目或较少的功能来说,这可能是矫枉过正。最简单的方法是karim's answer。另一方面,JSON-RPC 是一个标准。
回答by DisgruntledGoat
You can't call a PHP function with Javascript, in the same way you can't call arbitrary PHP functions when you load a page (just think of the security implications).
你不能用 Javascript 调用 PHP 函数,就像你不能在加载页面时调用任意 PHP 函数一样(想想安全隐患)。
If you need to wrap your code in a function for whatever reason, why don't you either put a function call under the function definition, eg:
如果出于某种原因需要将代码包装在函数中,为什么不将函数调用放在函数定义下,例如:
function test() {
// function code
}
test();
Or, use a PHP include:
或者,使用 PHP 包括:
include 'functions.php'; // functions.php has the test function
test();
回答by pocesar
You may use my library that does that automatically, I've been improving it for the past 2 years http://phery-php-ajax.net
您可以使用我的库自动执行此操作,过去 2 年我一直在改进它http://phery-php-ajax.net
Phery::instance()->set(array(
'phpfunction' => function($data){
/* Do your thing */
return PheryResponse::factory(); // do your dom manipulation, return JSON, etc
}
))->process();
The javascript would be simple as
javascript会很简单
phery.remote('phpfunction');
You can pass all the dynamic javascript part to the server, with a query builder like chainable interface, and you may pass any type of data back to the PHP. For example, some functions that would take too much space in the javascript side, could be called in the server using this (in this example, mcrypt, that in javascript would be almost impossible to accomplish):
您可以将所有动态 javascript 部分传递给服务器,使用类似可链接接口的查询构建器,并且您可以将任何类型的数据传递回 PHP。例如,一些在 javascript 端占用太多空间的函数可以在服务器中使用这个调用(在这个例子中,mcrypt,在 javascript 中几乎不可能完成):
function mcrypt(variable, content, key){
phery.remote('mcrypt_encrypt', {'var': variable, 'content': content, 'key':key || false});
}
//would use it like (you may keep the key on the server, safer, unless it's encrypted for the user)
window.variable = '';
mcrypt('variable', 'This must be encoded and put inside variable', 'my key');
and in the server
并在服务器中
Phery::instance()->set(array(
'mcrypt_encrypt' => function($data){
$r = new PheryResponse;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $data['key'] ? : 'my key', $data['content'], MCRYPT_MODE_ECB, $iv);
return $r->set_var($data['variable'], $encrypted);
// or call a callback with the data, $r->call($data['callback'], $encrypted);
}
))->process();
Now the variablewill have the encrypted data.
现在variable将拥有加密的数据。
回答by casperOne
You are going to have to expose and endpoint (URL) in your system which will accept the POST request from the ajax call in jQuery.
您将不得不在系统中公开端点(URL),该端点将接受来自 jQuery ajax 调用的 POST 请求。
Then, when processing that url from PHP, you would call your function and return the result in the appropriate format (JSON most likely, or XML if you prefer).
然后,当从 PHP 处理该 url 时,您将调用您的函数并以适当的格式返回结果(最有可能是 JSON,如果您愿意,也可以是 XML)。

