有没有办法在同一窗口中通过 ajax 提交从单独页面加载的表单?

我有这个表格:


<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 加载的,因此我不能专门将脚本附加到它,因为直到它出现在屏幕上,它在技术上并不存在。


富国沪深
浏览 134回答 1
1回答

aluckdog

如果我理解您的问题,您只想更新当前页面的一部分。如果是这样,您将不得不为此使用 AJAX:保留“提交”按钮,但将其设为标准按钮并为其指定一个 ID,例如“提交”:<button id="submit" name="submit" title="add to cart">Add to Cart</button>然后您的 JavaScript 将按如下方式处理按钮上的点击事件:$(function() {&nbsp; &nbsp; let submit = $('#submit');&nbsp; &nbsp; submit.click( function() { //&nbsp; &nbsp; &nbsp; &nbsp; submit.prop('disabled', true); // prevent a re-submission&nbsp; &nbsp; &nbsp; &nbsp; var form = $('#ajax');&nbsp; &nbsp; &nbsp; &nbsp; var request = $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: form.attr('action'), // get the action from the form&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: form.attr('method'), // get the method from the from&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataType: 'html', // the assumption is that we are dealing HTML here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: form.serialize()&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; request.done(function(ajaxResult) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // update the DOM with the results&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#some_div').html(ajaxResult); // replace contents of <div id="some_div"></div> with new html&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; submit.prop('disabled', false); // re-enable the submit&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });});您必须安排发回的结果只是需要更新的 HTML。更新自回复以来,您添加了一条带有链接的评论,表明我可能误解了您的意图。您使用的短语“提交表单但在提交时阻止它打开新页面”绝对可以使人理解我的原始解释。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript