AJAX POST到MVC控制器显示302错误 [英] AJAX POST to MVC Controller showing 302 error

查看:342
本文介绍了AJAX POST到MVC控制器显示302错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的MVC视图中执行AJAX POST.我写了以下内容:

I want to do AJAX POST in my MVC View. I've written the following:

视图中的脚本代码

$('#media-search').click(function () {
    var data = { key: $('#search-query').val() };

    $.ajax({
        type: 'POST',
        url: '/Builder/Search',
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            $('.builder').empty();
                alert("Key Passed Successfully!!!");
        }
    });
});

控制器代码

[HttpPost]
public ActionResult Search(string key)
{
    return RedirectToAction("Simple", new { key=key });
}

但是在AJAX POST上,我收到 302发现错误

But on AJAX POST I am getting the 302 found Error

推荐答案

"302"响应代码是重定向.您的控制器操作显式返回一个RedirectToAction,它仅返回302.由于此重定向指令是由AJAX调用而不是由浏览器直接使用的,因此,如果要重定向浏览器,则需要执行以下操作:

The '302' response code is a redirect. Your controller action explicitly returns a RedirectToAction, which simply returns a 302. Since this redirect instruction is consumed by your AJAX call and not directly by your browser, if you want your browser to be redirected, you will need to do the following:

$.ajax({
     type: 'POST',
     url: '/Builder/Search',
     data: JSON.stringify(data),
     dataType: 'json',
     contentType: 'application/json; charset=utf-8',
     success: function (data) {
          if (data.redirect) {
              window.location.href = data.redirect;
          }
          $('.builder').empty();
          alert("Key Passed Successfully!!!");
     }
});

否则,您将需要返回比控制器发出的重定向指令更有意义的内容.

If not, you'll need to return something more meaningful than a redirect instruction from your controller.

这篇关于AJAX POST到MVC控制器显示302错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆