問題描述
我正在返回一些需要由 javascript 處理的 json 作為對 XMLHTTPRequest 的響應.
如果我將響應的內容類型設置為text/plain",除 Chrome 之外的所有瀏覽器都會接受它并將其傳遞給我的 JS,沒有問題.但是,Chrome 會將響應包裝在
中在將其傳遞給我的 javascript 之前.
如果我將響應的內容類型設置為正確"應用程序/json",所有瀏覽器,但 Firefox 將接受它并將其傳遞給我的 JS,沒有問題.但是,Firefox 會要求將響應保存或打開為文件.
什么是正確的跨瀏覽器內容類型?
解決方案 您可以通過使用jQuery funcion parseJSON - http://api.jquery.com/jQuery.parseJSON/
您傳遞給函數的參數是 JSON 對象字符串,您從響應數據中提取:
function AjaxResponse (data) {//AJAX post 回調var jsonResult = $.parseJSON(data.substring(data.indexOf("{"), data.lastIndexOf("}") + 1));}
在 FF 和 IE8 中針對以下簡單 JSON 結果進行了測試(除了 Chrome 解決了哪個問題),對于其他瀏覽器和更復雜的響應,無法保證...
<小時>注意:我認為這種情況下的內容類型是 text/plain 或 text/html - 我使用了以下 ASP.Net MVC 函數來返回結果
ContentResult System.Web.Mvc.Controller.Content(string content);
我返回 JSON 對象的位置,如
System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer= 新 System.Web.Script.Serialization.JavaScriptSerializer();var jsonResponse = jsonSerializer.Serialize(新 { IArticleMediaId = 0, ImageUrl = Url.Content(fullImgPath)});返回內容(jsonResponse);
I am returning some json which needs to be handled by javascript as the response to an XMLHTTPRequest.
If I set the response's content type to "text/plain", all browsers but Chrome will accept it and pass it to my JS with no problem. However, Chrome will wrap the response in
<pre style="word-wrap: break-word; white-space: pre-wrap;">
before passing it to my javascript.
If I set the response's content type to the "proper" "application/json" all browsers but Firefox will accept it and pass it to my JS with no problem. Firefox, however will ask to save or open the response as a file.
What's the correct, cross-browser Content-Type?
解決方案 You may solve the issue by parsing the response into the JSON object by using jQuery funcion parseJSON - http://api.jquery.com/jQuery.parseJSON/
The parameter you pass into the function is the JSON object string, which you extract from the response data:
function AjaxResponse (data) { // AJAX post callback
var jsonResult = $.parseJSON(data.substring(data.indexOf("{"), data.lastIndexOf("}") + 1));
}
Tested (besides Chrome which problem this solves) in FF and IE8 for the following simple JSON result, for other browsers and more complex responses no guarantees...
NOTE: the content type in this case is text/plain or text/html I think - I've used the following ASP.Net MVC function to return the result
ContentResult System.Web.Mvc.Controller.Content(string content);
Where I returned the JSON object like
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);
這篇關于瀏覽器對 json ajax 響應的 Content-Type 標頭有什么要求?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!