简体   繁体   English

表单重定向Jquery Ajax

[英]Form Redirect Jquery Ajax

I'm working on an HTML app in which there is a form. 我正在开发具有表单的HTML应用程序。 On clicking the submit button, I make a server-side call using jquery.ajax() . 单击提交按钮后,我使用jquery.ajax()进行服务器端调用。 However, whenever an exception is returned from the server, like a Status Code 500 , I need to display an error message on the same page. 但是,无论何时从服务器返回异常,例如Status Code 500 ,我都需要在同一页面上显示错误消息。 However, it automatically redirects when it encounters an error. 但是,遇到错误时,它将自动重定向。 I tried using the statusCode setting in jquery.ajax() like this: 我尝试在jquery.ajax()中使用statusCode设置,如下所示:

$.ajax(
{
    method: 'GET',
    url: 'my url',
    //...
    successCode: {
        500: function(response) {
            alert(response.getResponseHeader("xyz"));
            $('some_selector').show();
        }
    },
    success: function(){},
    error: function(){}
    //...
}) 

But this does not seem to work. 但这似乎不起作用。 It redirects me to the action link and displays the JSON error and I cannot think of a way to prevent this redirect. 它将我重定向到操作链接并显示JSON错误,并且我想不出一种防止这种重定向的方法。 Any help would be appreciated. 任何帮助,将不胜感激。

Thanks 谢谢

It seems like your ajax options are outside of the ajax call put your parameters inside like 似乎您的ajax选项不在ajax调用的范围内,将您的参数放入
$.ajax(){options} => $.ajax({options}) $.ajax(){options} => $.ajax({options})

Try this, 尝试这个,

    $.ajax({url: 'your url',
        type: 'GET',
        success: function (response) {
            //succesfull request

        }
    }).fail(function (response) {
        //failed request
    });

You should be able to find the status code in the fail using response.status 您应该能够使用response.status在失败中找到状态代码

I think your submit button is triggering the redirect. 我认为您的“提交”按钮正在触发重定向。 Try adding 尝试添加

$("#myform").submit(function(event){
       event.preventDefault();  
});

to prevent the redirect 防止重定向

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM