如何使用我的javascript强制执行正确的顺序

How to force the proper order with my javascript

本文关键字:顺序 强制执行 何使用 我的 javascript      更新时间:2023-09-26

好的,所以我有这个JavaScript/jQuery

$('.next').click(function(e){
  e.preventDefault();
  var table = $('table.active');
  var form = table.find('form');
  form.submit();
  window.location.href = '/some/location';
});

问题是,在某些浏览器中,Safari是其中之一,form.submit()永远不会被调用。

我的猜测是,这是一个异步请求,从来没有机会进行该调用。

关于如何做到这一点的任何想法。我尝试了以下

  form.submit(function(){
     window.location.href = '/some/location';
  });

但是不起作用

您需要类似的东西

$(function() {
  $('.next').click(function(e){
    e.preventDefault();
    var table = $('table.active');
    var form = table.find('form');
    $.post(form.attr("action"),function() {
      window.location.href = '/some/location';
    });
  });
});

使用参数尝试

    $.post(form.attr("action"),form.serializeArray(),function() {

您可以通过AJAX做一些事情。

JavaScript/jQuery:

$(document).ready( function() {
    /* attach a submit handler to the form */
    $("#formID").submit(function(event) {
      /* stop form from submitting normally */
      event.preventDefault();
      /* get some values from elements on the page: */
      var $form = $( this ),
          term = $form.find( 'input[name="s"]' ).val(),
          url = $form.attr( 'action' );
      /* Send the data using post */
      var posting = $.post( url, { s: term } );
      /* Redirect the client */
      posting.done(function( data ) {
        window.location.href = '/some/location';
      });
 });

这在不同的浏览器中会有不同的行为,如果允许window.location中断请求,则允许重写表单的提交。

如果您打算将表单的内容作为ajax提交,则需要将表单字段收集到一个对象中,然后用ajax发送该对象,并在ajax请求中将该对象发送到服务器,成功后重定向到您想要的页面。

$.ajax({
  type: "POST",
  url: "some.php",
  data: stringifyedData
}).done(function ( data ) {
  window.location = "/some/location";
});

您需要在表单的action参数所在的页面上重定向到/some/location

您只需要延迟设置location.href,以便浏览器首先发送Ajax请求。您不需要等待响应:

setTimeout(function(){
    window.location.href = '/some/location';
}, 1);