简体   繁体   English

如何通过ajax调用多个PHP函数,最佳实践?

[英]How to call multiple PHP functions through ajax, best practices?

I have some ajax calls in multiple JavaScript functions.我在多个 JavaScript 函数中有一些 ajax 调用。 Each one does a post / get to a functions.php file每个人都做一个帖子/获取一个functions.php文件

The functions.php has multiple functions that should correspond with the ones from JavaScript. functions.php 有多个函数,应该与 JavaScript 中的函数相对应。

For example in js I have:例如在js中我有:

function one() {
$.ajax({ 
    type: 'POST', 
    url: 'http://www.example.com/functions.php', 
    data: vals,
    dataType:'json',
    success: function (data) {
        alert(data);
    }
});
}

function two() {
$.ajax({ 
    type: 'POST', 
    url: 'http://www.example.com/functions.php', 
    data: othervals,
    dataType:'json',
    success: function (data) {
        alert(data);
    }
});
}

function three() {
$.ajax({ 
    type: 'GET', 
    url: 'http://www.example.com/functions.php',  
    data: { get_param: 'user' },
    dataType:'json',
    success: function (data) { 
        alert(data);
    }
        
});
}

In PHP I have something like this:在 PHP 中我有这样的东西:

if (isset($_POST['city'])) {  // this comes from the javascript vals json object
$city = $_POST['city'];
   function one() {
    // do something

    return true;
   }
}

function two() {
 // do something
 return true;
}


if (isset($_GET['get_param']) && $_GET['get_param'] == 'user'){
function three() {
 // do something
return true;
}
}

Maybe the PHP side is a bit confusing the way I write it, but in the end I want the function one to only deal with the corespondent function from the PHP file.也许 PHP 方面我写它的方式有点混乱,但最后我希望function one处理 PHP 文件中的 corespondent 函数。 Obviously they don't need to have the same name.显然,它们不需要具有相同的名称。

The PHP functions can return true or false or 1 or 0 , and that suppose to be the alerted data alert(data); PHP 函数可以返回truefalse10 ,并且假设是警报数据alert(data); . .

If there is more confusion on what I want please let me know and I'll clarify.如果对我想要的东西有更多的困惑,请告诉我,我会澄清的。

Why not split the PHP functions in separate smaller scripts?为什么不将 PHP 函数拆分为单独的较小脚本? They stand for different endpoints in your application and cannot be called together, so they should not be together.它们代表应用程序中的不同端点,不能一起调用,因此它们不应该在一起。

Have you checked out a REST library style.您是否检查过 REST 库样式。 It looks like your doing basically that but a bit more confusing.看起来你基本上是这样做的,但有点混乱。 When i say REST library i do not mean a purely RESTful library, but instead each function in your back-end is navigable via url.当我说 REST 库时,我并不是指纯粹的 RESTful 库,而是后端中的每个函数都可以通过 url 导航。

The way your doing it is fine (as long as the functions data does not depend on any other function data (as it could lead to some funny results)).你这样做的方式很好(只要函数数据不依赖于任何其他函数数据(因为它可能导致一些有趣的结果))。 Its just a lot easier to do more of a restful approach.做更多的宁静方法要容易得多。 Its fairly simple to set up a rest library.建立一个休息库相当简单。

I just find that doing the whole $_POST[...] and then keep doing it is just cumbersome over time and becomes harder and harder to manage, because there is always some new twist on what is needed then you end up with 100's of methods for taking care of calling back end functions.我只是发现做整个 $_POST[...] 然后继续做会随着时间的推移变得很麻烦,并且变得越来越难以管理,因为总是需要一些新的变化,然后你最终会得到 100 个处理调用后端函数的方法。

MyApi = {    
    /**
     * The API Version
     */
    API_VERSION: "0.5",
    SITE_URL: "http//myurl.com/",
    /**
     * The API URL
     */
    apiURL: function(tokens) {
        return MyApi.SITE_URL + MyApi.API_VERSION + "/api/" + MyApi.apiTokenizer(tokens);
    },
    /**
     * The tokenizer for the API.
     */
    apiTokenizer: function(tokens) {
        var str = '';
        $.each(tokens, function(key, value) {
            str += value + "/";
        })
        return str;
    }
}

Thats the javascript for producing new api links, then you could have something like那就是用于生成新 api 链接的 javascript,然后你可以有类似的东西

function callBackend(tokens) {
    $.ajax({ 
        type: 'POST', 
        url: MyLibrary.apiURL(tokens),
        dataType:'json',
        success: function (data) {
            alert(data);
        }
    });
}

On your backend you would need an .htaccess file like so在您的后端,您需要一个像这样的 .htaccess 文件

RewriteRule 0\.5/(.*) api/_MyApi.php?v=0\.5&state=$1 [QSA]

Then you could write a back end switch statement that would take apart the state (delimiters would be "/") that would navigate you to the end time library call.然后,您可以编写一个后端 switch 语句,该语句将分解状态(分隔符将是“/”),将您导航到结束时间库调用。

<?php
    $state = MyParser::Parse($_REQUEST["state"]);
    $output = array();
    switch ($state) {
        case "case1":
            //do stuff
            break;
    }

    echo json_encode($output);
?>

That way output is always handled the same way.这样输出总是以相同的方式处理。


Just as a note.就像一个注释。 That was a very VERY simple and INCOMPLETE implementation, but i find that its a lot easier to maintain than a $_POST that goes to 1 of 100 different files that all have very similar output and all of that.这是一个非常简单且不完整的实现,但我发现它比 $_POST 更容易维护,它可以访问 100 个不同文件中的 1 个,这些文件都有非常相似的输出等等。

Cheers!干杯! Happy coding快乐编码

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

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