使用jQuery $ .ajax来调用一个PHP函数

这可能是一个简单的答案,但我使用jQuery的$ .ajax来调用一个PHP脚本。 我想要做的事情基本上把PHP脚本放在一个函数中,并从JavaScript调用PHP函数。

<?php if(isset($_POST['something'] { //do something } ?> 

对此

 <?php function test() { if(isset($_POST['something'] { //do something. } } ?> 

我将如何在JavaScript中调用该函数? 现在我只是使用$ .ajax列出的PHP文件。

使用$.ajax调用服务器上下文(或URL,或其他)来调用特定的“操作”。 你想要的东西是这样的:

 $.ajax({ url: '/my/site', data: {action: 'test'}, type: 'post', success: function(output) { alert(output); } }); 

在服务器端,应该读取action POST参数,相应的值应该指向要调用的方法,例如:

 if(isset($_POST['action']) && !empty($_POST['action'])) { $action = $_POST['action']; switch($action) { case 'test' : test();break; case 'blah' : blah();break; // ...etc... } } 

我相信这是命令模式的简单化身。

我开发了一个jQuery插件,允许你调用任何核心PHP函数甚至用户定义的PHP函数作为插件的方法: jquery.php

将jquery和jquery.php包含在我们的文档头部并将request_handler.php放在我们的服务器上之后,我们将按照下面描述的方式开始使用插件。

为了便于使用,以简单的方式参考该function:

  var P = $.fn.php; 

然后初始化插件:

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

现在有一些使用场景:

 // 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 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"] 

演示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 ); 

演示如何发送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 ); 

后端configuration提供了一个白名单,所以你可以限制哪些function可以被调用。 还有一些与插件描述的PHP一起工作的其他模式。

我会坚持正常的方法来直接调用文件,但如果你真的想调用一个函数,看看JSON-RPC (JSON远程过程调用)。

你基本上发送一个特定格式的JSONstring到服务器,例如

 { "method": "echo", "params": ["Hello JSON-RPC"], "id": 1} 

其中包括调用函数和该函数的参数。

当然,服务器必须知道如何处理这样的请求。
这里是JSON-RPC的jQuery插件 ,例如Zend JSON Server作为PHP中的服务器实现。


这可能是一个小项目或更less的function矫枉过正。 最简单的方法是karim的答案 。 另一方面,JSON-RPC是一个标准。

你不能用Javascript调用一个PHP函数,就像你在加载一个页面时不能调用任意PHP函数一样(只是想到安全性的含义)。

如果你需要将代码封装在一个函数中,为什么不把函数调用放在函数定义之下,例如:

 function test() { // function code } test(); 

或者,使用PHP包括:

 include 'functions.php'; // functions.php has the test function test(); 

你可以使用我的图书馆自动执行,我已经改善了过去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(); 

JavaScript将是简单的

 phery.remote('phpfunction'); 

您可以将所有dynamicJavaScript部分传递给服务器,并使用可链接接口等查询构build器,并且可以将任何types的数据传递回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'); 

并在服务器中

 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(); 

现在variable将具有encryption的数据。

您将不得不在系统中公开和端点(URL),它将接受来自jQuery中的ajax调用的POST请求。

然后,当从PHP处理这个url时,你会调用你的函数,并以适当的格式返回结果(最有可能的是JSON,或者如果你愿意,可以是XML)。