【发布时间】:2009-07-06 17:27:28
【问题描述】:
出于调试目的,我正在尝试使用 $.ajax 而不是 getJSON。因为 getJSON 在 IE(6,7 或 8)中没有报错,我想弄清楚为什么一个 jQuery 插件没有将我返回的图像在 IE 中绘制到屏幕上,而是在其他浏览器中。
所以我尝试了这个。有趣的是,它在 IE 中遇到了错误事件,但在 firefox、safari 等中却没有,我不知道为什么(这段代码运行良好,在 FireFox 和其他部分中可以很好地呈现我的数据)。我知道我返回的 json 是有效的:
$.ajax({
type: "GET",
url: "http://localhost:59396/sss/sssHandler.ashx?action=getproducts&ids=" + ids,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data.length);
carousel.size(allProductIDs.length);
if (numberOfImagesLeftToShow < numberOfImagesToDisplay) {
first += (numberOfImagesToDisplay - numberOfImagesLeftToShow);
}
var d = 0;
for (var i = first; i <= last; i++) {
if (d != undefined) {
// add data using index of the array returned by JSON (which starts at 0)
carousel.add(i, decode(data[d].ImageTag));
}
// set to last ProductID showing in Carousel
if (i == last) { lastProductID = parseFloat(data[d].ProductID); }
d++;
}
},
error: function() {
alert("An error has occurred. Please try again.");
}
});
我不知道还能做些什么来解决为什么 IE 在返回的 JSON 上遇到这么多问题,或者只是使用 getJSON 或 this 来执行函数(数据)。我也在响应中设置了标题而不是缓存。那不是问题。 问题是由于某种原因,IE 拒绝在响应中输入我的函数(数据)。
这是显示有效的返回 JSON(甚至使用 http://www.jsonlint.com/ 进行检查):
[
{
"ImageTag": "\u003cdiv class=\"CarouselItem
\"\u003e<p><img src="http://www.xxx.com/image/
2568.jpg" alt=""></p>\u003cp\u003e\u003ca href=
\"Bear-10.prod\"\u003eTeddy Bear\u003c/a\u003e\u003c/p\u003e\u003cp
\u003e$20.95\u003c/p\u003e\u003cdiv\u003e",
"ProductID": "540"
},
{
"ImageTag": "\u003cdiv class=\"CarouselItem
\"\u003e<p><img src="http://www.xxx.com/image/
50.jpg" alt=""></p>\u003cp\u003e\u003ca href=
\"Pendant362.prod\"\u003eBirthday\u003csup\u003e©\u003c/sup
\u003Necklace\u003c/a\u003e\u003c/p\u003e\u003cp\u003e$36.95\u003c/p
\u003e\u003cdiv\u003e",
"ProductID": "83"
}
]
在我的 .ashx 中,我只需使用以下主要代码来生成响应
context.Response.ContentType = "application/json";
context.Response.Charset = Encoding.UTF8.ToString();
context.Response.Cache.SetNoStore();
context.Response.Cache.SetExpires(DateTime.MinValue);
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Cache.SetValidUntilExpires(false);
context.Response.Expires = -1;
context.Response.ExpiresAbsolute = DateTime.MinValue;
context.Response.AddHeader("Cache-Control", "no-cache");
context.Response.AddHeader("Cache-Control", "post-check=0, pre-check=0");
context.Response.AddHeader("Pragma", "no-cache");
...
string jsonString = imageList.ToJSON(); <-- uses the .NET 3.5 JavaScriptSerializer
context.Response.Write(jsonString);
此外,将 response.ContentType 指定为“application/json”还是“text/plain”似乎并不重要,因为至少我在 FireFox 中得到了返回和解析的有效数据。
【问题讨论】:
标签: jquery