2010-02-15 174 views
103

这可能是一个简单的答案,但我使用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文件。

+5

通过PHP javascript生成的PHP代码被评估,或者以相反的方式进行,这是一个非常糟糕的主意。 – 2010-02-15 22:18:10

+0

你能解释为什么这样不好吗? – Catfish 2010-02-15 22:22:57

+3

因为任何人都可以将任何代码放在您的代码的位置,因此他们可以对您的服务器做坏事。 – 2010-02-15 22:27:20

回答

207

使用$.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... 
    } 
} 

我相信这是一个简单的化身Command pattern

+8

哎呀。所以你不能直接用js选择哪个函数在PHP中调用,你只能用PHP来获取post值并以这种方式调用函数。谢谢 – Catfish 2010-02-16 18:19:15

+0

但是,如果你使用框架,这很简单。以Kohana为例,您可以简单地调用控制器/动作 ajax(function(){url:'Controller/action.php', }); – DeathCoder 2014-04-22 10:49:30

+3

应更新以反映现代最佳实践 – MrMesees 2016-06-16 23:36:49

2

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

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

4

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

您基本上会以特定的格式向服务器发送JSON字符串,例如

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

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

当然,服务器必须知道如何处理这些请求。
这里是jQuery plugin for JSON-RPC和例如在PHP中用Zend JSON Server作为服务器实现。


这可能是一个小项目或更少的功能矫枉过正。最简单的方法是karim's answer。另一方面,JSON-RPC是一个标准。

+0

非常感谢,很久以前我一直在寻找这个解决方案.. – 2013-09-07 14:58:38

3

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

如果你需要用你的代码的功能是什么原因,你为什么不要么把函数定义下一个函数调用,如:

function test() { 
    // function code 
} 

test(); 

或者,使用PHP包括:

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

你可以用我的库,这是否自动,我一直在改进它在过去的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'); 

您可以通过所有动态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'); 

和在服务器中

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将具有加密数据。

10

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

包括jQuery和jquery.php在我们的文档的头部和在放置后request_handler.php在我们的服务器上,我们将以下面描述的方式开始使用插件。

为了便于使用,引用功能以简单的方式:

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

后端配置提供白名单,以便限制其功能可以被调用。还有一些与插件描述的PHP一起工作的其他模式。

+0

谢谢你已经做得很好。 – 2016-09-07 23:57:03