[英]How to get the JSON response using same AJAX mechanism
here is the Ajax code i use 这是我使用的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){
}
At the beginning of the page load, i call mainCall()
. 在页面加载的开始,我调用
mainCall()
。 When i call the same system with XML format this functions works perfectly. 当我用XML格式调用同一系统时,此功能可以完美运行。 But when i call with JSON format, then
firstPageData(resJSON)
, resJSON
becomes null. 但是当我使用JSON格式调用时,那么
firstPageData(resJSON)
, resJSON
变为null。
any ideas? 有任何想法吗?
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);
}
}
This worked !!, I found it in JavaScript: The Definitive Guide: The Definitive Guide 这有效!!,我在JavaScript中找到了它:权威指南:权威指南
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.