我有这个表格:
<form method="post" action="/cart" id="ajax">
{...}
<div>
{{ product.option | hidden_option_input }}
</div>
<button name="submit" type="submit" title="add to cart">Add to Cart</button>
</form>
该表单是通过ajax加载到页面的,其操作页面也是通过ajax在导航栏中的另一个链接中预加载的。我想提交表单,但是阻止表单在提交时打开新页面。我该怎么办?我尝试过:
<a href="/cart" class="new_popup mfp-ajax" onclick="this.parentNode.submit();return false;">Add to Cart</a>
替换按钮,但是即使我尝试使用“ return false;”来否定默认行为,点击后仍会重新加载新页面。我可以在刚加载新页面之前看到链接的弹出窗口,但是直到新页面出现后它才提交。我相信这是因为当用户单击链接到表单时,该表单是通过ajax加载的,因此,我无法将脚本附加到其上,因为在屏幕上显示该表单在技术上并不存在。
答案 0 :(得分:1)
如果我理解您的问题,则只想更新当前页面的一部分。如果是这样,您将必须为此使用AJAX:
保留“提交”按钮,但将其设置为标准按钮,并为其提供一个ID,例如“提交”:
<button id="submit" name="submit" title="add to cart">Add to Cart</button>
然后,您的JavaScript将按以下方式处理按钮上的click事件:
$(function() {
let submit = $('#submit');
submit.click( function() { //
submit.prop('disabled', true); // prevent a re-submission
var form = $('#ajax');
var request = $.ajax({
url: form.attr('action'), // get the action from the form
type: form.attr('method'), // get the method from the from
dataType: 'html', // the assumption is that we are dealing HTML here
data: form.serialize()
});
request.done(function(ajaxResult) {
// update the DOM with the results
$('#some_div').html(ajaxResult); // replace contents of <div id="some_div"></div> with new html
submit.prop('disabled', false); // re-enable the submit
});
});
});
您必须安排发送回的结果只是需要更新的HTML。
更新
自回复以来,您添加了带有链接的评论,表明我可能误解了您的意图。您使用的短语“提交表单,但阻止提交时打开新页面”绝对可以使我理解原来的意思。