简体   繁体   English

结合两个ajax函数?

[英]Combining two ajax functions?

I have a website which has, amongst others, two pages: an event booking page and a login page. 我有一个网站,其中有两个页面:活动预订页面和登录页面。

My goal: I want to declare two Ajax functions, loginUser() and bookEvent(), that I can use on any page, also in combination. 我的目标:我想声明两个Ajax函数,loginUser()和bookEvent(),它们可以在任何页面上使用,也可以结合使用。 When the user clicks "login" on the login page, only the loginUser() function shall be executed, when user clicks "book event" on the event booking page, first it should be checked if the user is logged-in, then if he is not logged in he shall have the opportunity to login (invoking the loginUser function) and once he has logged in he will automatically have booked the event (invoking bookEvent function). 当用户在登录页面上单击“登录”时,仅将执行loginUser()函数,当用户在事件预订页面上单击“预订事件”时,首先应检查用户是否已登录,然后检查他没有登录,他将有机会登录(调用loginUser函数),一旦登录,他将自动预​​订该事件(调用bookEvent函数)。

My question: How can I combine both functions in the latter case? 我的问题:在后一种情况下,如何合并两个功能? And how can achieve that if the user is already logged in, on the events booking page only the bookingEvent() function gets fired when the user clicks on "book event"? 如果用户已经登录,那么如何实现呢?在用户单击“预订事件”时,在事件预订页面上仅会激活bookingEvent()函数? I am not asking for the php code, I already know how to use both functions separately from one another and how to connect to the database! 我不是在要求php代码,我已经知道如何将两个函数彼此分开使用以及如何连接到数据库!

Here is what I have come up with so far: 到目前为止,这是我想出的:

My two general customizable functions: 我的两个常规可自定义函数:

// LOGIN USER FUNCTION
function loginUser(login_query, param_response_dberror, 
param_response_failed, param_response_success) {

        $.ajax({
                type : "POST",
                url : "system/process-login.php",
                data : login_query,
                cache : false,
                success : function(ajaxresponse) {
                                if (ajaxresponse === 'db_error') {
                                    param_response_dberror();
                                }
                                if (ajaxresponse === 'failed') {
                                    param_response_failed();
                                }
                                if (ajaxresponse === 'success') {
                                    param_response_success();
                                }
                            }
                        });

} // /function loginUser();

// BOOK EVENT FUNCTION
function bookEvent (booking_query, param_response_dberror, 
param_response_failed, param_response_success) {

        $.ajax({
                type : "POST",
                url : "system/process-booking.php",
                data : booking_query,
                cache : false,
                success : function(ajaxresponse) {
                                if (ajaxresponse === 'db_error') {
                                    param_response_dberror();
                                }
                                if (ajaxresponse === 'failed') {
                                    param_response_failed();
                                }
                                if (ajaxresponse === 'success') {
                                    param_response_success();
                                }
                            }
                        });

} // /function bookEvent();

My page frontend: 我的页面前端:

<h1>Some event</h1>
<p>Some event description</p>

<a href="#">book event</a>

<div id="loginbox" style="display:none">
<input type="text" id="username" placeholder="username">
<input type="password" id="password" placeholder="password">
<a href="#" id="login_and_book">login and book</a>
</div>

First, it should be checked if the user is logged-in. 首先,应检查用户是否已登录。

  • If he is not logged-in: Make the login box visible and when the user clicks "login and book" he gets logged in AND books the event . 如果他未登录:使登录框可见,并且当用户单击“登录并预订”时, 他将登录并预订事件 How can I combine both when the user clicks the button? 当用户单击按钮时,如何合并两者?
  • If he is already logged-in: Book the event. 如果他已经登录:预定活动。

This sounds like a poster-child for jQuery "Promises" , although it's complicated by the fact that even your "error" conditions look like "successes" at the AJAX layer. 听起来这听起来像是jQuery“ Promises”的后代 ,尽管由于您的“错误”条件在AJAX层上看起来像“成功”,这一事实使情况变得复杂。

You will need to maintain some browser-side state to indicate whether the user has successfully logged in or not, initially false , and set to true in the "success" branch of the loginUser function. 您将需要维护一些浏览器端状态,以指示用户是否已成功登录,最初为false ,并在loginUser函数的“ success”分支中设置为true You must of course also maintain this state on the server too, to avoid the possibility of the user bypassing the login requirement by hacking code on the client side. 当然,您还必须在服务器上也维护此状态,以避免用户通过在客户端修改代码来绕过登录要求的可能性。

I suggest also separating your success and failure conditions, and use promises to achieve "separation of concerns": 我建议也将您的成功和失败条件分开,并使用诺言来实现“关注点分离”:

var loggedIn = false;

// returns promise that will be resolved by logging in via AJAX,
// or automatically resolved if the user was already logged in
function loginUser(login_query) {
    var def = $.Deferred();
    if (loggedIn) {
        def.resolve();
    } else {
        $.ajax({
            type : "POST",
            url : "system/process-login.php",
            data : login_query,
            cache : false
        }).then(function(ajaxresponse) {
            if (ajaxresponse === 'success') {
                loggedIn = true;
                def.resolve();
            } else {
                def.reject(ajaxresponse);
            }
        });
    }
    return def.promise();
};

Modify the bookEvent function similarly, and then when the "book event" button is pressed, use something like this: 相似地修改bookEvent函数,然后在按下“ book event”按钮时,使用如下代码:

function autoBook() {
    return loginUser(login_query).then(bookEvent);
}

Please note - this example is very incomplete . 请注意-此示例非常不完整 You will need to arrange for the appropriate query parameters to be sent, and for callbacks to be invoked based on the (eventual) results received from the promises. 您将需要安排发送适当的查询参数,并根据从promise收到的(最终)结果来调用回调。

AJAX is by definition asynchronous, so even if you could combine them into one function, there is no guarantee that either one would always be received first (eg: login might process AFTER booking, etc.). 根据定义,AJAX是异步的,因此即使您可以将它们组合为一个功能,也无法保证始终会首先接收到其中一个(例如:登录可能在预订后处理,等等)。 Your best bet is to put one inside the other -- specifically in the success callback. 最好的选择是将两者放在一起-特别是在成功回调中。

This begs the question of how you are logging your users in, though; 但是,这引出了您如何登录用户的问题; if you are using a redirect of some sort, then trying to combine them is pointless as after the user is redirected the previous AJAX call would be forfeit. 如果您使用某种重定向,则尝试将它们合并是没有意义的,因为在用户重定向之后,先前的AJAX调用将被取消。 If you are simply lumping the user login information onto the booking form, why not have a case server-side that checks if the user "lump" is in the data you sent it? 如果只是将用户登录信息汇总到预订表中,为什么不让案例服务器端检查用户“汇总”是否在您发送的数据中?

Here is a bit on "parallel" AJAX requests , but I think what you are really looking for is a "sequential" AJAX queue (which is demonstrated in the same link). 这是关于“并行” AJAX请求的一些内容 ,但是我认为您真正要寻找的是“顺序” AJAX队列(在同一链接中进行了演示)。

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

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