ライブラリを使用せずに Http リクエストを作成しています (別のスクリプトで競合が発生していました...)
しかし、オブジェクトのスコープに問題があります。以下は呼び出しスクリプトで、その後に Ajax_Request オブジェクトが続きます。
function loadCard(e) {
var element = e.target;
if($('overlay')) {
return false; //something is already over the layout
}
var card = '/card/'+element.id;
var option = {method:'post', parameters:'test', async:true}
loadOverlay();
var ajax = new Ajax_Request(card, option);
}
//Ajax_Request
function Ajax_Request(url, options) {
if(typeof url !== 'undefined') {
this.url = url;
}
if(typeof options.method !== 'undefined') {
this.method = options.method;
} else {
this.method = 'get';
}
if(typeof options.parameters !== 'undefined') {
this.parameters = options.parameters;
}
if(typeof options.async !== 'undefined') {
this.async = true;
} else {
this.async = false;
}
if(window.XMLHttpRequest) {
this.request = new XMLHttpRequest();
} //check for MS browser
this.makeRequest = function() {
try {
this.request.onreadystatechange = this.checkReadyState;
this.request.open(this.method, this.url, this.async);
if(this.method == 'post') {
this.request.send(this.parameters);
} else {
this.request.send(null);
}
} catch(err) {
alert(err);
}
}
this.setResponse = function(r) {
alert(r)
this.response = r;
}
this.getResponse = function() {
return this.responseText;
}
this.checkReadyState = function(r) {
switch(this.readyState) {
case 4:
//Represents a "loaded" state in which the response has been completely received.
if(this.status == 200) {
this.setResponse(this.responseText)
}
...
}
}
}
呼び出し元のオブジェクトが動作できるように、応答をプロパティに設定しようとしています。しかし、this.setResponse() を呼び出そうとすると、未定義であるというエラーが表示されます。onreadystatechange コールバックをプログラムに正しく関連付けるにはどうすればよいですか?
それ以外の場合、スクリプトはデータを適切に返すので、そのまま出力することもできますが、もう少し柔軟性が必要です。
ありがとうリッチ