我想爲Chrome擴展創建一個簡單的ajax類。當我嘗試運行代碼時,出現未定義的錯誤Uncaught TypeError: Cannot read property 'readyState' of undefined
。什麼似乎導致這個問題?在javascript中構建一個簡單的ajax類
function ajax(arguments, callback) {
this.xhr = new XMLHttpRequest();
this.xhr.open(arguments.requestType, arguments.requestUrl + arguments.requestParameters, true);
this.xhr.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
requestedData = JSON.parse(this.responseText);
callback(requestedData);
}
}
this.xhr.send();
}
var ajaxRequest = new ajax({
requestType: 'GET',
requestUrl: 'http://ezswag.com/bots/terms.php',
requestParameters: ' ',
}, function(json) {
//console.log(json); => json {apple: "red", cheery: "red"}
return json;
});
console.log(ajaxRequest);
(更新代碼,工作)
謝謝。我用回調更新了代碼。有沒有辦法從變量'ajaxRequest'的函數之外的回調中訪問json數據? –