[英]How to get the JSON response using same AJAX mechanism
這是我使用的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
變為null。
有任何想法嗎?
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中找到了它:權威指南:權威指南
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.