我有一个javascript,它在“提交”事件上执行以下ajax调用(进而触发python脚本),我现在的问题是“当一个提交事件发生时,如果其他人点击 这个ajax调用的提交按钮应该通知提交正在进行中”,有人遇到过这个问题吗?(有名字吗?),如何解决这个问题? 请建议..
$("#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++;
}
最佳答案
好吧,只要你想同步所有用户的请求处理,就应该在服务器端完成。我假设你的服务器端是Python,即使你没有在你的问题中添加相关标签。我的偏好是 C# 和 PHP,但在你的情况下我会执行以下操作...
选项#1 - session
1)添加或安装Python优选的 session 模块,人群推荐使用Beaker
Python Module for Session Management
2)发送AJAX请求到服务器端脚本
$(form).submit(function(e) {
var options = {
url: "scripts/cherrypick.py"
};
$.ajax(options);
});
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
- Bottle.py session with Beaker
- http://beaker.readthedocs.org/en/latest/sessions.html#using
- http://flask.pocoo.org/snippets/61/
4) 现在,在你的 JS 脚本中,如果你得到包含关键“处理”的 JSON,你可能会向用户显示警报,他需要等待第一个请求被处理
选项#2 - 长轮询和 Comet
这个选项的描述可能需要更多的篇幅来描述,因此最好看看这篇文章,它有相当漂亮和干净的例子以及Python中长轮询的实现
http://blog.oddbit.com/2013/11/23/long-polling-with-ja/
这里的主要思想不是保持静态 session ,而是使用无限循环,它可以根据某些状态变量发回不同的 HTTP 响应:
@route('/cherrypick')
def index():
while True :
response = { 'processing': processing }
print response
if processing != 1 :
processing = 1
# Do some processing
processing = 0
sleep(5)
关于javascript - 互斥提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30633032/