简体   繁体   English

Internet Explorer中的Ajax和JSON响应错误(适用于所有其他浏览器)

[英]Ajax and JSON response bug in Internet Explorer (works in all other browsers)

For some reason IE is asking us to download a file instead of running it as ajax. 出于某种原因,IE要求我们下载文件而不是将其作为ajax运行。 This works in all browsers except IE. 这适用于IE以外的所有浏览器。 I tried messing with the headers that it returns with no luck. 我试着弄乱它没有运气的标题。

The function grabs form data then post's it the response is a can be an array of any number of items to be updated on the page. 该函数抓取表单数据然后发布它的响应是可以是在页面上要更新的任意数量项目的数组。

Its not suppose to be file its suppose to be just a json response. 它不应该是文件,它假设只是一个json响应。

PHP PHP

header('Content-type: application/json');

$error = "The Email and Password you entered could not be resolved.";
$elements[0]['target'] = '.error_report';
$elements[0]['action'] = 'inside';
$elements[0]['data'] = '<p>'.$error.'</p>';
$this->output->set_output(
  json_encode(array("elements" => $elements))
);

Javascript 使用Javascript

$(document).ready(function () {
    jQuery.ajaxSetup({
        cache: false,
        dataType: 'json',
        error: function () {
            alert("Request was not successful. Please try again shortly.");
        }
    });

    $(document).ajaxSuccess(function (e, xhr, settings) {
        var response = xhr.responseText;
        if (settings.dataType != 'json') {
            return;
        };

        try {
            response = jQuery.parseJSON(response);
        } catch (e) {
            alert(e);
            return;
        }

        if (response.elements instanceof Array) {
            var reqs = ['target', 'action'];
            var valid = true;
            for (var i=0;i<response.elements.length;i++) {
                var cur = response.elements[i];
                var sel;

                for (var j=0;j<reqs.length;j++) {
                    if (typeof cur[reqs[j]] !== "string") {
                        valid = false;
                        break;
                    };
                };

                if (!valid) {
                    continue;
                };

                sel = $(cur.target);
                switch (cur.action) {
                    case "inside":
                        sel.html(cur.data);
                    break;
                    case "instead":
                        sel.replaceWith(cur.data);
                    break;
                    case "remove":
                        sel.remove();
                    break;
                    case "refreshPage":
                        window.location.reload();
                    default:
                        if (typeof sel[cur.action] === "function") {
                            sel[cur.action](cur.data);
                        }; // else continue
                    break;
                };
            };
        };


            // Dispatch the AJAX request, and save it to the data object so that
            // is can be referenced and cancelled if need be.

            self.data('ajaxify.xhr', jQuery.ajax({
                url: this.action,
                type: 'post',
                dataType: options.dataType,
                data: (beforeSubmitIsJquery ? beforeSubmitResult.serialize()
                                            : self.serialize()),
                success: function (/**/) {
                    cleanup();

                    options.onSuccess.apply(that, arguments);
                },
                error: function (/**/) {
                    cleanup();

                    options.onError.apply(that, arguments);
                },
                complete: function (/**/) {
                    options.onComplete.apply(that, arguments);
                }
            }));

Well, I ask because the behavior you describe has all the hallmarks of a double-post caused by an event handler launching an ajax request followed by the "native" browser form submit happening. 好吧,我问,因为你描述的行为具有双重帖子的所有标志,这是由事件处理程序启动ajax请求后跟“本机”浏览器表单提交发生的。 If I were you, I'd make triple-extra-sure that your event handler is either returning "false" or calling "preventDefault", or maybe both :-) – Pointy 1 hour ago 如果我是你,我会做三倍 - 确保您的事件处理程序返回“false”或调用“preventDefault”,或者两者兼而有之:-) - Pointy 1小时前

My followup: Since IE ignores preventDefault, try using return false; 我的后续:由于IE忽略了preventDefault,请尝试使用return false; after preventDefault ... 在preventDefault之后......

For future reference to other devs: the way that the common libraries tend to do this is they will usually code a block with both methods (preventDefault() and return false;) because this tells each of the major browsers to stop working the event, according to which they listen to. 为了将来引用其他开发人员:公共库倾向于这样做的方式是他们通常用两种方法编码一个块(preventDefault()并返回false;)因为这会告诉每个主要的浏览器停止工作,据他们所听。 This is more important with legacy IE browsers. 对于传统的IE浏览器,这一点更为重要。

Anyways, glad we could help. 无论如何,很高兴我们可以帮忙。

I had this problem with ASP.NET MVC 4. I was returning a JSONResult. 我在ASP.NET MVC 4中遇到了这个问题。我正在返回一个JSONResult。 But by changing the return object to this.content fixed this problem. 但是通过将返回对象更改为this.content修复了这个问题。

[HttpPost]
public ActionResult Upload(AddNewModel model)
{
    /**...*/
    return this.Content(id.ToString());
}

So it appears that IE has a problem with a json object being returned, and can be fixed by returning a string. 所以看来IE有一个返回json对象的问题,可以通过返回一个字符串来修复。

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

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