【问题标题】:AJAX: Loading URL on submit button clickedAJAX:单击提交按钮时加载 URL
【发布时间】:2016-04-06 11:12:42
【问题描述】:

我正在尝试加载/重定向另一个页面/站点,具体取决于成功或错误。 首先它总是执行错误块,虽然我检查了控制台我在那里找不到任何错误。和 其次,它不会重定向到使用“windows.location.href('URL');”指定的 URL

$(document).ready(function() { $("#login-form").on("submit", function(e) { e.preventDefault(); var name = $('#name').val(); var email = $('#email').val(); $.ajax({ type: 'POST', dataType: 'jsonp', url: 'http://localhost:8080/AppBot/AnswerHandler', data: 'operation=login' + '&name=' + name + '&email=' + email, success: function() { alert('Success'); }, error: function() { alert('Failure'); window.location.href = 'https://www.google.com'; } }); }); });

【问题讨论】:

  • window.loaction.href 应该是 window.location.href
  • 哦……我的错。无论如何,谢谢。

标签: javascript java jquery ajax


【解决方案1】:

如下修改您的代码以修复you had typo error in window.loaction.href中的拼写错误:

$(document).ready(function() {
    $("#login-form").on("submit", function(e) {
        e.preventDefault();
        var name = $('#name').val();
        var email = $('#email').val();

        var request = $.ajax({
            method: "POST",
            type: 'POST',
            dataType: 'jsonp',
            url: 'http://localhost:8080/AppBot/AnswerHandler',
            //pass your data as an array
            data: { operation : 'login', name : name, email: email },
            beforeSend: function ( xhr ) {
                //$('#loading').show();
            }
        });

        request.done(function( response ) {                

            console.info('Success');
            console.log(response);
        });

        request.fail(function( jqXHR, textStatus ) {
            alert( "Color request failed: " + textStatus );
            window.location.href = 'https://www.google.com';
        });


    });
});

【讨论】:

  • 所以现在第一个问题解决了。但它总是执行错误块。
  • 尝试使用 {operation:'login', name:name, email:email} 将数据作为对象传递
  • @SagarGalande 我已经更新了 ajax 代码,请尝试使用它,检查您在控制台中得到的内容。并检查您正在调用的脚本,它应该返回一个 json 编码数据
  • @SagarGalande,你在 firebug 的控制台中得到了什么?
  • 等等,我正在尝试这个新脚本
【解决方案2】:

试试这个

$(document).ready(function(){
    $("#login-form").on("submit",function(e){
        e.preventDefault();
        var name = $('#name').val();
        var email = $('#email').val();
       $.ajax({
          method: "POST",
          url: "http://localhost:8080/AppBot/AnswerHandler",
          data: { operation: 'login', name: name, email:email}
        })
          .done(function( msg ) {
            alert('Success');
          });
    });
});

【讨论】:

  • 我的意思是ajax执行错误块,虽然控制台上没有错误
  • 使用这个数据类型:'json',
  • 第二个问题解决了,只是拼写错误。但是第二个还没解决
猜你喜欢
  • 2018-08-27
  • 2020-01-30
  • 1970-01-01
  • 2012-03-29
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2016-08-03
  • 2018-02-16
相关资源
最近更新 更多