简体   繁体   English

互斥提交

[英]Mutually exclusive submits

I have a javascript which on a "submit" event does the following ajax call(which in turn triggers a python script),my problem now is that "when one submit event is going on if anyone else clicks on the submit button this ajax call should notify that a submission is in progress" ,has anyone ran into this problem?(is there a name?) ,how do fix this problem? 我有一个javascript,它在“ submit”事件上执行以下ajax调用(这又触发了python脚本),我现在的问题是“如果有人在提交事件上单击其他人单击此ajax调用,应该通知提交中”。是否有人遇到此问题?(有名字吗?),如何解决此问题? Please suggest.. 请建议..

$("#main_form").submit(function(event) {
       .....................

            $.ajax({
                dataType: "json",
                type: "POST",
                contentType: "application/json",//note the contentType definition
                url: "scripts/cherrypick.py",
                data: JSON.stringify(data_cp),
                //data: data_cp,
                error : function (xhr, ajaxOptions, thrownError){
                    console.log("cherypick fail");
                    console.log(response);      
                    console.log(response['returnArray']);
                    alert(xhr.status);
                    alert(thrownError); 
                },
                success: function(response){
                    console.log("cherypick sucess");
                    console.log(response);
                    console.log(response['returnArray']);
                    var return_array = response['returnArray'];
                    console.log(return_array['faillist'].length);
                    console.log(return_array['picklist'].length);       
                    for (var i = 0; i < ip_gerrits.length; ) {
                        for (var j = 0; j < return_array['faillist'].length; ) {
                            if (ip_gerrits[i] != return_array['faillist'][j] )
                                ipgerrits_pickuplist.push(ip_gerrits[i]);
                            j++;
                        }
                        i++;
                    }

Ok, as far as you want to synchronize requests processing for all users, it should be done on the server side. 好的,就您要同步所有用户的请求处理而言,应该在服务器端完成。 I assume that your server side is Python, even though you did not add relevant tag to your question. 我假设您的服务器端是Python,即使您没有在问题中添加相关标签。 My preferences are C# and PHP, but in your case I would do the following ... 我的偏好是C#和PHP,但在您的情况下,我将执行以下操作...

Options # 1 - Session 选项#1-会话

1) add or install preferable session module for Python, crowd recommends to use Beaker 1)为Python添加或安装首选的会话模块,人群建议使用Beaker

Python Module for Session Management 用于会话管理的Python模块

2) send AJAX request to the server side script 2)发送AJAX请求到服务器端脚本

$(form).submit(function(e) {

    var options = {
         url: "scripts/cherrypick.py"
    };

    $.ajax(options);

});

3) this server side script will have something like this code 3)此服务器端脚本将具有类似以下代码的内容

session_opts = {
    'session.type': 'file',
    'session.data_dir': './session/',
    'session.auto': True,
}

app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)

@hook('before_request')
def setup_request():
    request.session = request.environ['beaker.session']

@route('/cherrypick')
def index():
    if 'processing' in request.session:
        data = { 'procesing': request.session['processing'] }
        return data

    processor()

def processor():

    request.session['processing'] = 1

    # Do some processing here for the first request
    # When processing is done you can clear "state" variable in session

    del request.session['processing']
    request.session.modified = True

4) Now in your JS script if you get JSON that contains key "processing" you may show alert to the user that he needs to wait until first request is processed 4)现在,在JS脚本中,如果您获取包含键“处理中”的JSON,则可能会向用户显示警告,他需要等待直到处理第一个请求

Option # 2 - Long Polling and Comet 选项2-长轮询和彗星

Description of this option may take much more space to describe, thus it is better to look at this article, it has quite nice and clean example and implementation of long polling in Python 此选项的描述可能需要更多的空间来描述,因此最好看一下这篇文章,它有一个非常漂亮,干净的示例以及在Python中进行长轮询的实现

http://blog.oddbit.com/2013/11/23/long-polling-with-ja/ http://blog.oddbit.com/2013/11/23/long-polling-with-ja/

The main idea here is not to keep static session but use infinite loop instead that can send back different HTTP responses depending on some state variable : 这里的主要思想不是保持静态会话,而是使用无限循环,它可以根据某些状态变量发送回不同的HTTP响应:

@route('/cherrypick')
def index():

    while True :

        response = { 'processing': processing }
        print response

        if processing != 1 :
            processing = 1
            # Do some processing
            processing = 0

        sleep(5)

The simplest way is to close around a flag that indicates some processing is underway: 最简单的方法是关闭一个标志,该标志指示正在进行某些处理:

var processing = false;   
$("#main_form").submit(function(event) {
    if (processing) {
        $("#some_notification_pane").text("hold on there, turbo!");
        return;
    }
    processing = true;
    ...
    $.ajax({
        ...
        error: function(xhr, ajaxOptions, thrownError) {
            ...
            processing = false;
        },
        success: function(response) {
            ...
            processing = false;
        }
    });
    ...
});

You might also want to disable the submit button at the beginning of the submit handler (where I have processing = true ) and re-enable it after receiving a response. 您可能还想在提交处理程序(在其中我正在processing = true )的开头禁用提交按钮,并在收到响应后重新启用它。

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

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