在JSON成功的情况下重定向到其他地方?

时间:2017-11-19 06:08:50

标签: javascript jquery html json forms

我的代码:

<script>
  $('#form').submit(function() {
    $.ajax({
      type: 'POST',
      url: $(this).attr('action'),
      dataType: 'json',
      success: function(json) {
        window.location.href = "http://www.example.com";
      }
    });
    return false;
  });
</script>

表格:

<form id="form" class="center" action="http://localhost/products/index.php?route=checkout/cart/add" method="post">
  <input type="text" name="cname">
  <input type="hidden" name="product_id" value="51">
  <input type="submit">
</form>

当表单按下提交时,它会转到仅仅是JSON成功消息的操作页面,我想要做的是重定向到除操作页面之外的其他页面,但我的代码似乎不起作用?< / p>

我的代码究竟出了什么问题,有人可以帮我解决吗?

如果你能帮助我,我将非常感激,非常感谢!

3 个答案:

答案 0 :(得分:2)

您没有发布任何使POST无用的数据。

你也没有错误处理程序

尝试:

$(function(){
    $('#form').submit(function() {

       var $form = $(this);

        $.ajax({
            type: 'POST',
            url: $form.attr('action'),

            // data to send
            data: $form.serialize(),

            dataType: 'json',
            success: function(json) {
               window.location.href = "http://www.example.com";
            },
            error: function(){
               // do something when request fails - See $.ajax docs
            }
        })
        return false;
    });
});

答案 1 :(得分:0)

您可以使用此代码进行错误处理!您还可以在stackOverflow上查看此问题,以便使用jQuery / JavaScript重定向到另一个页面: click here

$('#form').submit(function() {
  var $form = $(this);
  $.ajax({
    type: 'POST',
    url: $form.attr('action'),

    // data to send
    data: $form.serialize(),
    dataType: 'json',
    success: function(json) {
      window.location.href = "http://www.example.com";
    },
    error: function (jqXHR, exception) {
      var msg = '';
      if (jqXHR.status === 0) {
        msg = 'Not connect.\n Verify Network.';
      } else if (jqXHR.status == 404) {
        msg = 'Requested page not found. [404]';
      } else if (jqXHR.status == 500) {
        msg = 'Internal Server Error [500].';
      } else if (exception === 'parsererror') {
        msg = 'Requested JSON parse failed.';
      } else if (exception === 'timeout') {
        msg = 'Time out error.';
      } else if (exception === 'abort') {
        msg = 'Ajax request aborted.';
      } else {
        msg = 'Uncaught Error.\n' + jqXHR.responseText;
      }
      alert(msg);
    },
  });
});

答案 2 :(得分:0)

您需要具有单独的错误和成功处理程序,如下所示。 在成功方法中,您可以重定向到其他页面/网站(window.location.href =&#34; http://www.EXAMPLE.com&#34 ;;)

var ajaxUpdateRequest = {
url: '/dotnethelpers/UpdateUsers',
dataType: 'json',
success: updateSuccessfully, //Separate method for handling success
error: showError //Separate method for handling error
}; 
相关问题