getJSON是jQuery提供的一个简化方法,用于发起AJAX请求并期望返回JSON格式的数据。AJAX(Asynchronous JavaScript and XML)是一种在不重新加载整个页面的情况下与服务器交换数据并更新部分网页的技术。
IE9及更早版本在AJAX请求方面存在以下主要问题:
JSON.parse()
和JSON.stringify()
方法// 添加JSON支持(如果不存在)
if (!window.JSON) {
window.JSON = {
parse: function(sJSON) { return eval("(" + sJSON + ")"); },
stringify: (function() {
var toString = Object.prototype.toString;
var isArray = Array.isArray || function(a) { return toString.call(a) === "[object Array]"; };
var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'};
var escFunc = function(m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
return function stringify(value) {
if (value == null) return "null";
var type = typeof value;
if (type === "boolean") return value + "";
if (type === "number") return isFinite(value) ? value + "" : "null";
if (type === "string") return '"' + value.replace(escRE, escFunc) + '"';
if (typeof value.toJSON === "function") return stringify(value.toJSON());
if (isArray(value)) {
var res = "[";
for (var i = 0; i < value.length; i++)
res += (i ? ", " : "") + stringify(value[i]);
return res + "]";
}
var tmp = [];
if (typeof value === "object") {
for (var k in value) {
if (value.hasOwnProperty(k))
tmp.push(stringify(k) + ": " + stringify(value[k]));
}
return "{" + tmp.join(", ") + "}";
}
return "null";
};
})()
};
}
$.ajaxSetup({
cache: false, // 禁用缓存
dataType: "json",
beforeSend: function(xhr) {
// 添加时间戳参数防止缓存
if (this.type.toLowerCase() == 'get') {
this.url += (this.url.indexOf('?') > 0 ? '&' : '?') + '_=' + new Date().getTime();
}
}
});
// 兼容IE9的AJAX请求
function makeAjaxRequest(url, callback) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
// 对于IE6及更早版本
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
callback(data);
} else {
console.error("Request failed with status: " + xhr.status);
}
}
};
xhr.send();
}
$.ajax({
url: 'your-api-endpoint',
type: 'GET',
dataType: 'json',
cache: false,
success: function(data) {
// 处理数据
},
error: function(xhr, status, error) {
console.error("Error:", error);
}
});
通过以上方法,可以解决大多数IE9中getJSON或AJAX请求的问题。
没有搜到相关的沙龙