这是我使用的Ajax代码
function AJAXInteraction(url, callback) {
var req = init();
req.onreadystatechange = processRequest;
function init() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest () {
// readyState of 4 signifies request is complete
if (req.readyState == 4) {
// status of 200 signifies sucessful HTTP call
if (req.status == 200) {
if (callback) callback(req.responseXML);
}
}
}
this.doGet = function() {
req.open("GET", url, true);
req.send(null);
}
}
function mainCall(){
var req_url = "requestItems.php?format=json&num=100"
var ajax = new AJAXInteraction(req_url, firstPageData);
ajax.doGet();
}
function firstPageData(resJSON){
}
在页面加载开始时,我调用mainCall()
。当我使用XML格式调用相同的系统时,此功能可以完美运行。但是当我使用JSON格式调用时,firstPageData(resJSON)
,resJSON
变为空。
任何想法?
答案 0 :(得分:1)
function processRequest () {
// readyState of 4 signifies request is complete
if (req.readyState == 4) {
// status of 200 signifies sucessful HTTP call
if (req.status == 200) {
var type = req.getResponseHeader("Content-Type");
if (type.indexOf("xml") !== -1 && req.responseXML)
callback(req.responseXML);
else if (type=== "application/json")
callback(JSON.parse(req.responseText));
else
callback(req.responseText);
//if (callback) callback(req.responseXML);
}
}
这很有效!!我在 JavaScript: The Definitive Guide: The Definitive Guide
中找到了它