我有一个程序增强的表单,使用jQuery发布(当启用javascript时)。
当javascript被禁用时,一切正常。
<form class="clearfix" action="https://examples.com/api/rest/members/memberidnotshownforsecurity/examples/?on_success=https://examples.com/account/examples?alerts=inserted&on_failure=https://examples.com/error" method="POST" onsubmit="return false;">
<input id="url" type="text" name="example_url" placeholder="paste a link to example it"><br>
<button id="insertExample" type="button">create</button>
</form>
当#insertExample按钮被点击时,jQuery处理请求。
<script type="text/javascript">
$(document).ready(function() {
var insertExampleMutex = false;
$("#insertExample").on('click', null, function(event) {
if ( insertExampleMutex == false ) {
insertExampleMutex = true;
var reference = $(this);
var progsubmit = reference;
var progform = progsubmit.parents('form');
var progmethod = progform.attr('method');
var progaction = progform.attr('action').substring( 0, progform.attr('action').indexOf('?') );
var progdata = progform.serialize();
var inventory = reference.parents('#core').find('#inventory');
progsubmit.html('loading...');
$.ajax({
type: progmethod,
url: progaction,
data: progdata,
dataType: 'json'
}).done(function(data) {
if ( data.status == '1' ) {
inventory.prepend('<div style="cursor: pointer;" id="selectExample" href="' + "https://examples.com" + '/api/rest/members/' + data['data']['member_examples']['member_id'] + '/examples/' + data['data']['member_examples']['example_id'] + '" class="alert bgsuccess"><center><p class="psmall">A new example was created. Click to here display.</p></center></div>');
} else {
inventory.prepend('<div style="cursor: pointer;" onclick="window.location.reload();" class="alert bgfailure"><center><p class="psmall">An error occurred.</p></center></div>');
}
}).fail(function() {
inventory.prepend('<div style="cursor: pointer;" onclick="window.location.reload();" class="alert bgfailure"><center><p class="psmall">An error occurred.</p></center></div>');
}).always(function() {
progform[0].reset();
progsubmit.html('create');
inventory.children('p').remove();
insertExampleMutex = false;
});
}
});
});
</script>
问题是.failure()请求处理程序被触发…尽管发帖成功了。第二个问题是,它不仅是一次成功,而且是两次成功。
在数据库中创建了两个具有相同数据的条目,当然除了id。
我搜索了一下,但没有发现任何结论。
我已经使用了一个互斥变量来忽略多个请求。
表单没有被浏览器和javascript提交。两者都源于ajax调用(这似乎是不可能的,因为互斥变量)
我读到Ajax可能会得到一个301,这将导致它再次发布到重定向的url,但这似乎不是情况。
根据我的经验,如果处理来自服务器的成功响应的javascript失败,则会触发失败处理程序。换句话说,服务器可以是成功的,但是如果客户端不能正确处理它,就会触发错误事件。你可以尝试使用chrome或firebug或其他工具来调试在响应上触发的javascript。
我遇到了双击问题时,$(文档)。Ready函数不止触发一次。例如,如果您发布的脚本块在某些HTML中包含了多次,这将导致您的代码被连接多次。
同样,您可以在文档中插入一个断点。