简体   繁体   English

Howto:PHP / Javascript通讯

[英]Howto: PHP/Javascript communication

As I'm developing my WebIDE , I keep coming up with questions that I cannot answer myself. 在开发WebIDE时 ,我不断提出自己无法回答的问题。 This is because the project is supposed to help others create what they would "normally" create, but faster (ie as automated as possible). 这是因为该项目应该帮助其他人创建他们“正常”创建的内容,但要更快(即尽可能自动化)。 In this light, my question is how to you implement a PHP backend? 有鉴于此,我的问题是如何实现PHP后端?

Here is what I do. 这是我的工作。 I like to create "functions" that the client JavaScript can call. 我喜欢创建客户端JavaScript可以调用的“函数”。 Usually, I send (via POST and JSON) a variable called "action" which holds the name of the "function" I am calling (as well as any arguments I wish to send it). 通常,我(通过POST和JSON)发送一个名为“ action”的变量,其中包含我正在调用的“函数”的名称(以及我希望发送的任何参数)。 The PHP code, then, looks something like this: 然后,PHP代码如下所示:

if(issset($_POST['action'])) {
    //function foo(arg1,arg2)
    if($_POST['action'] == 'foo') {
        $arg1 = $_POST['arg1'];
        $arg2 = $_POST['arg2'];
        //do stuff
    }
}

I can still reference other real functions I create in PHP, but I find that this is a nice way to organize everything and easy to implement in both JavaScript and PHP. 我仍然可以引用我在PHP中创建的其他实际函数,但是我发现这是一种组织所有内容的好方法,并且易于在JavaScript和PHP中实现。

What do you do? 你是做什么?

Edit 1: Ok, based on the first two answers to this question, I do not think I am explaining myself well. 编辑1:好的,基于对这个问题的前两个答案,我认为我不能很好地解释自己。

I am asking how do you create a PHP back end. 我问您如何创建PHP后端。 The idea is that you have your AJAX client written in JavaScript (or maybe something else, it doesn't matter ), and then it will call your backend PHP with POST or GET data. 这个想法是,您有用JavaScript编写的AJAX客户端(或其他无关紧要的东西),然后它将使用POST或GET数据调用后端PHP。 Based on this data, your backend will do what it needs to do (maybe it will simply update the database, and maybe even return information, again: it doesn't matter ). 根据这些数据,您的后端将执行所需的操作(也许它将仅更新数据库,甚至可能会再次返回信息: 没关系 )。

The question now is: how do you tell it what to do? 现在的问题是:您如何告诉它该怎么做? What do you send via POST/GET and how do you interpret it in your backend? 您通过POST / GET发送什么,以及如何在后端解释它?

I send all data to the backend in a big GET array. 我将所有数据发送到大型GET数组中的后端。

actionpage.php?action=post&parameters[parameter1]=value1&parameters[parameter2]=value2 actionpage.php?action = post&parameters [parameter1] = value1&parameters [parameter2] = value2

If you print_r($_GET), on the PHP side you'll see: 如果您使用print_r($ _ GET),则在PHP方面,您将看到:

array(
    "action" => "create",
    "parameters" => array("parameter1"=>"value1","parameter2"=>"value2")
)

What this does is allow you to loop through your parameters. 这样做是允许您遍历参数。 You can say in the pap 你可以说在爸爸

 if($_GET['action'] == 'create'){
      foreach($_GET['parameters'] as $key=>$value){ //something

this website will answer all your ajax questions. 该网站将回答您所有的ajax问题。 I found it really helpful. 我发现它真的很有帮助。 http://ajaxpatterns.org/XMLHttpRequest_Call http://ajaxpatterns.org/XMLHttpRequest_Call

The question now is: how do you tell it what to do? 现在的问题是:您如何告诉它该怎么做? What do you send via POST/GET and how do you interpret it in your backend? 您通过POST / GET发送什么,以及如何在后端解释它?

Choose your own conventions. 选择您自己的约定。 For example use an "action" value in your JSON data that tells the action, then add more parameters. 例如,在JSON数据中使用一个“操作”值来告知操作,然后添加更多参数。 You can spy on various websites's Ajax messages with Firebug extension in Firefox if you want to see what other websites do. 如果您想查看其他网站的功能,则可以在Firefox中监视带有Firebug扩展名的各个网站的Ajax消息。

For example the Json POST data could be: 例如,Json POST数据可以是:

{
    action: "create",
    fields: {
       firstname: "John",
       lastname: "Doe",
       age: 32
    }
}

To which you could reply with the ID of the newly created record. 您可以向其回复新创建的记录的ID。

To delete the record: 删除记录:

{
    action: "delete",
    keys: {
        id: 4654564
    }
}

etc. 等等

In the php ajax handler you could have something as simple as a switch: 在php ajax处理程序中,您可以像开关一样简单:

$jsonData = Services_Json::decode($_POST['json']);
switch ($jsonData->action)
{
    case "save":
        if (validate_json_data($jsonData->fields))
        {
            UsersPeer::create($jsonData->fields);
        }
        break;
    case "delete":
        /* etc */
}

// return a json reply with 
$jsonReply = new stdClass;
$jsonReply->status = "ok";
$jsonReply->statusMessage = "Record succesfully created";
echo Services_Json::encode($jsonReply);
exit;

Javascript, say prototype Ajax.Request responder function will output the error message in a specially created DIV if "status" is not "ok", etc... Java语言,例如原型Ajax.Request响应器功能,如果“状态”不是“确定”,则会在专门创建的DIV中输出错误消息,等等。

You need to organize functions? 您需要组织功能吗? It's called 'class'. 这就是所谓的“阶级”。

/// todo: add error processing
$name=$_GET['action'];
$args=json_decode($_GET['args']); /// or just subarray, doesn't matter

/// 'Action' is constant here but in reality you will need more then one class for this
/// because you will want modules in your framework
if(method_exists('Action',$name))
    call_user_func_array(array('Action',$name),$args);
else { /* incorrect parameters processing */ }

/// Ajax-available functions are here
class Action
{
    public static function action1()
    {
        echo 'action1';
    }
    public static function action2()
    {
        echo 'action2';
    }
}

I use a front page controller which handles my routing. 我使用处理我的路由的首页控制器。 If you set up mod-rewrite you can have very clean endpoints where the first segment of your url refers to the controller (class) and then the subsequent segments would refer to the methods inside followed by the parameters being passed to the method. 如果您设置mod-rewrite,则可以有非常干净的终结点,其中url的第一段引用控制器(类),然后随后的段引用内部的方法,然后是传递给该方法的参数。

http://domain.com/class/method/param1/param2 http://domain.com/class/method/param1/param2

I do something very similar. 我做的事情很相似。 What you need is a JSON object to pass back to the javascript. 您需要一个JSON对象传递回javascript。 When you are done with your PHP, you can call json_encode to pass an object back to the front end. 完成PHP后,可以调用json_encode将对象传递回前端。 From there you can do more with it in Javascript or format it however you want. 从那里,您可以使用Javascript对其进行更多处理,或者根据需要对其进行格式化。

There is more information on a similar question here: Best way to transfer an array between PHP and Javascript 这里有一个类似问题的更多信息: 在PHP和Javascript之间传输数组的最佳方法

Edit: After reading your edit, I think what you are doing is fine. 编辑:看完您的编辑后,我认为您在做什么。 When you send the AJAX request from Javascript include a variable like "action", or whatever youd like. 当您从Javascript发送AJAX请求时,请添加一个变量,例如“ action”,或任何您想要的变量。 From there you can check what the action is via a case and switch statement. 在这里,您可以通过case和switch语句检查操作的内容。

I usually write the php functions as normal functions. 我通常将php函数编写为普通函数。

fn1(arg1, arg2){
 //do stuff here
}
fn2(arg3){
 //do stuff here
}

I pass the name of the function in a variable called action. 我在一个名为action的变量中传递函数的名称。 Then do this: 然后执行以下操作:

foreach($_POST as $key => $value) 
$$key = $value;

To assign create variables of the same name as the arguments. 分配与参数同名的创建变量。

Then use a switch-case to call the appropriate function like so: 然后使用开关盒来调用适当的函数,如下所示:

switch($action){
 case 'fn1':fn1(arg1,arg2);
 break;
 case 'fn2':fn2(arg3);
 break;
}

Is this what you are looking for? 这是你想要的?

Edit: You could use the PHP SOAP and XML-RPC extension to develop a webservice, where if you specify the function name in the SOAP request, that function will be automatically executed (you don't have to write the switch-case or if). 编辑:您可以使用PHP SOAP和XML-RPC扩展来开发Web服务,如果您在SOAP请求中指定函数名称,则该函数将自动执行(您不必编写switch-case或)。 I've used it in Java, but am not sure how exactly it works in PHP. 我已经在Java中使用了它,但是不确定在PHP中它如何工作。

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

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