浏览器对json ajax响应的Content-Type标头需要什么?

问题描述 投票:8回答:2

我正在返回一些需要通过javascript处理的json作为对XMLHTTPRequest的响应。

如果我将响应的内容类型设置为“text / plain”,那么除Chrome之外的所有浏览器都会接受它并将其传递给我的JS而没有任何问题。但是,Chrome会将响应包装在中

<pre style="word-wrap: break-word; white-space: pre-wrap;"> 

在将它传递给我的javascript之前。

如果我将响应的内容类型设置为“正确的”“application / json”所有浏览器,但Firefox会接受它并将其传递给我的JS而没有任何问题。但是,Firefox会要求将响应保存或打开为文件。

什么是正确的跨浏览器内容类型?

ajax json cross-browser xmlhttprequest content-type
2个回答
7
投票

您可以通过使用jQuery funcion parseJSON将响应解析为JSON对象来解决问题 - http://api.jquery.com/jQuery.parseJSON/

传递给函数的参数是JSON对象字符串,您可以从响应数据中提取该字符串:

function AjaxResponse (data) {  // AJAX post callback 
  var jsonResult = $.parseJSON(data.substring(data.indexOf("{"), data.lastIndexOf("}") + 1));
}

在FF和IE8中测试(除了Chrome解决的问题)以下简单的JSON结果,对于其他浏览器和更复杂的响应没有保证......


注意:在这种情况下的内容类型是text / plain或text / html我认为 - 我使用了以下ASP.Net MVC函数来返回结果

ContentResult System.Web.Mvc.Controller.Content(string content);

我在哪里返回JSON对象

System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer 
    = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonResponse = jsonSerializer.Serialize(
    new { IArticleMediaId = 0
        , ImageUrl = Url.Content(fullImgPath)
        });
return Content(jsonResponse);

0
投票

在uploadCallback()中的ajaxFileUpload.js中替换

io.contentWindow.document.body.innerHTML.innerHTML

$(io.contentWindow.document.body.innerHTML).html()
© www.soinside.com 2019 - 2024. All rights reserved.