FireFox 和 IE9 尝试下载或显示 json-response,而不是让 javascript 解析它

发布于 2024-11-26 08:24:58 字数 1907 浏览 0 评论 0原文

更新

我的问题是我使用 event.preventDefault() 而不是 return false 来阻止表单正常发布。 FF 和 IE 不喜欢这样,并通过该行破坏了 JS。我删除了它并在最后附加了 return false ,这解决了问题。感谢 Darin Dimitrov 提供了详尽的清单。

原始问题

我正在使用 ASP.NET MVC3 和 jquery ajax 将 json 数据发布到服务器并接收响应。但是,当我使用 Chrome 时,它​​会正常读取 json-response,更新我想要的 div 等。但对于 IE 和 FF,它不起作用。他们只阅读响应并仅在页面上显示该响应。

我看到其他一些线程提到将 mime 类型定义为“text/plain”。这改变了之前提示用户下载 json-response 的行为。

这是用于发布帖子的 javascript:

 $.ajax({
        url: $("#formRegister").attr("action"),
        type: 'POST',
        data: JSON.stringify(user),
        dataType: 'json',
        contentType: 'application/json, charset=utf-8',
        traditional: true,
        success: function (data) {
            alertMessage(data.Message);

        },
        error: function () {

        }
    });

这是接收调用并返回 JsonResponse 的 ActionMethod:

[HttpPost]
    public JsonResult Register(UserRegisterPackage package)
    {
        ClientAlert alert = new ClientAlert();
        if (package.Password != null)
        {       
            //bool success = Removed for simplicity's sake.
            bool success = true;
            if (success)
            {                    
                alert.Message = "Success!";                    
            }
            else
            {                    
                alert.Message = "Failed to register";                    
            }
        }
        else
        {                
            alert.Message = "You need to enter a password!";                
        }
        return Json(alert, "text/plain");
    }

正如我所说,当内容类型定义为 text/plain 时,浏览器仅显示响应,当未定义时,它会提示用户下载 json-response 来代替。

对于 FF,我似乎收到一个错误:

"event is not defined
event.preventDefault(); "

这可能与错误有关..但我需要阻止表单正常发布。 FF 或 IE 中的做法是否不同?

有什么想法吗?

Update

My problem was that I used event.preventDefault() instead of return false to hinder the form from posting normally. FF and IE didn't like that and broke the JS by that line. I removed that and appended return false at the end and this solved the problem. Thanks to Darin Dimitrov for the extensive checklist.

Original question

I'm using ASP.NET MVC3 and jquery ajax to post json-data to the server and receive a response. However, when I'm using Chrome it reads the json-response normally, updating the divs that I want etc. With IE and FF it doesn't work though. They read just the response and shows only that on the page.

I saw some other threads mentioning to define the mime type as "text/plain". This changed the previous behavior of prompting the user to download the json-response instead.

This is the javascript for making the post:

 $.ajax({
        url: $("#formRegister").attr("action"),
        type: 'POST',
        data: JSON.stringify(user),
        dataType: 'json',
        contentType: 'application/json, charset=utf-8',
        traditional: true,
        success: function (data) {
            alertMessage(data.Message);

        },
        error: function () {

        }
    });

This is the ActionMethod receiving the call and returning a JsonResponse:

[HttpPost]
    public JsonResult Register(UserRegisterPackage package)
    {
        ClientAlert alert = new ClientAlert();
        if (package.Password != null)
        {       
            //bool success = Removed for simplicity's sake.
            bool success = true;
            if (success)
            {                    
                alert.Message = "Success!";                    
            }
            else
            {                    
                alert.Message = "Failed to register";                    
            }
        }
        else
        {                
            alert.Message = "You need to enter a password!";                
        }
        return Json(alert, "text/plain");
    }

As I said, when the content type is defined as text/plain the browser shows only the response and when it's not defined it prompts the user to download the json-response instead.

With FF I seem to get an error about:

"event is not defined
event.preventDefault(); "

This could have something to do with the error.. but I need to prevent the form from posting normally. Is this done differently in FF or IE?

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

奢华的一滴泪 2024-12-03 08:24:58

要尝试的事情:

  1. 如果此 $.ajax 调用是在某个锚点或 .click.submit 处理程序内进行的。 form> 确保最后返回 false;,以便取消默认行为并为 AJAX 请求的执行留出时间。您使用的 attr('action') 让我相信情况确实如此。
  2. 删除 traditional: true 参数,您正在发送 JSON 请求 =>这是无关紧要的。
  3. 确保您的页面上没有其他 JavaScript 错误,因为它们可能会停止 js 执行并继续正常表单提交
  4. 如果您打算返回 JSON,请从服务器中删除所有 text/plain。这样做是没有意义的,而且绝对不是你的问题的根源。只需使用return Json(alert);即可。

因此,如果您正在对表单进行 AJAX 化,您甚至不需要任何 JSON 请求,简单地说:

$('#formRegister').submit(function() {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function (data) {
            alertMessage(data.Message);
        },
        error: function () {

        }
    });
    return false;
});

如果您打算发送 JSON 请求,那么您的代码似乎没问题,jsu 确保没有其他 JS 错误。

Things to try:

  1. If this $.ajax call is made inside the .click or .submit handler of some anchor or <form> make sure you return false; at the end in order to cancel the default behavior and leave time for your AJAX request to execute. The attr('action') that you are using leaves me to believe that this is the case.
  2. Remove traditional: true parameter, you are sending a JSON request => it is irrelevant.
  3. Make sure there aren't some other javascript errors on your page as they might stop js execution and proceed into normal form submission
  4. Remove all text/plain from your server if you intend to return JSON. It's meaningless to do something like this and it's definitely not where your problem comes from. Simply use return Json(alert);.

So if you are AJAXifying a form you don't even need any JSON requests, simply:

$('#formRegister').submit(function() {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function (data) {
            alertMessage(data.Message);
        },
        error: function () {

        }
    });
    return false;
});

and if you intend to send JSON requests then your code seems fine, jsu make sure there aren't some other JS errors.

围归者 2024-12-03 08:24:58

我遇到了同样的问题,“JsonRequestBehavior.AllowGet”在 chrome 上运行良好,但在 IE 上失败。我尝试了多种格式,但以下是唯一适用于 IE 的格式。

return Json(additionalData, "text/html")

I faced the same problem where "JsonRequestBehavior.AllowGet" worked great on chrome, but fails on IE. i tried many formats, but below is the only one worked for IE.

return Json(additionalData, "text/html")
乖乖公主 2024-12-03 08:24:58

我在使用旧版本的 jQuery.Validate 时遇到了这个问题,这与设置不正确的数据类型中的错误有关。

确保您使用的是最新版本的 jQuery.validate

I encountered this when using an older version of jQuery.Validate, something to do with a bug in there setting the incorrect dataType.

Make sure you are using the latest version of jQuery.validate

染火枫林 2024-12-03 08:24:58

返回 Json(alert, "text/plain");

通常 Json(alert) 应该足够了。你可以尝试使用 application/json; charset=utf-8 作为内容类型?

return Json(alert, "text/plain");

Usually Json(alert) should be enough. Can you try with application/json; charset=utf-8 as a content type?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文