我只是在学习JavaScript对象并遇到问题/疑问。我有以下代码/ js对象:
已更改:这是完整的代码 - 它是Appcelerator Titanium项目!:
spike.xhr = spike.xhr || {};
spike.xhr.init = function() {
this.severResponse = '';
this.xhrMethod = 'GET';
}
spike.xhr.isOnline = function() {
if( Titanium.Network.online ) {
return true;
} else {
return false;
}
}
spike.xhr.notOnline = function() {
var alertDialog = Titanium.UI.createAlertDialog({
title: CONFIG.PROJECT_SHORT,
message: 'You do not have an online connect. Please connect...',
buttonNames: ['Continue'],
cancel: 0
});
alertDialog.show();
}
spike.xhr.connect = function( url ) {
if( spike.xhr.isOnline() ) {
spike.xhr.clients = Ti.Network.createHTTPClient();
spike.xhr.clients.onload = function() {
if (spike.xhr.clients.status != 200 && spike.xhr.clients.status != 201) {
var alertDialog = Titanium.UI.createAlertDialog({
title: CONFIG.PROJECT_SHORT,
message: 'We are sorry, but we have received an status error!',
buttonNames: ['Continue'],
cancel: 0
});
alertDialog.show();
return false;
}
this.serverResponse = this.responseText;
}
spike.xhr.clients.onerror = function(e) {
Ti.API.log( 'ERROR: ' + e.status + ': ' + e.statusText + ' - ' + e.error );
}
spike.xhr.clients.open( this.xhrMethod, url );
spike.xhr.clients.send();
} else {
spike.xhr.notOnline();
}
}
spike.xhr.basicAuthentication = function( username, password ) {
authstr = 'Basic ' +Titanium.Utils.base64encode( username+':'+ password);
spike.xhr.client.setRequestHeader( 'Authorization', authstr );
}
spike.xhr.setMethod = function( type ) {
this.xhrMethod = type;
}
spike.xhr.response = function() {
return this.serverResponse;
}
如果我现在跑:
spike.xhr.connect( 'http://mydomain' );
theResponse = spike.xhr.response();
我退回了<null>
! - 为什么我没有得到"This is a Test!"
或更好的问题:
我需要更改什么才能获得"This is a Test!"
?
答案 0 :(得分:3)
上述代码不起作用的原因是因为您的spike.xhr.connect
函数是异步。这意味着您可以告诉浏览器发出请求,但在浏览器等待响应返回时继续执行其他操作。
JavaScript在单个线程中运行,这意味着您一次只能执行一件事。某些操作(如“AJAX”调用)是异步,因为浏览器知道如何发出该请求,但不会阻止当前运行的代码等待请求。通常,使用回调函数调用异步代码,该函数在返回请求时运行 :
// pseudo code.
spike.xhr.connect( 'http://google.com', function ( response ) {
alert( 'google' );
});
alert( 'this will fire before spike.xhr.connects callback' );
当来自服务器的响应返回时,将执行回调函数 AND 浏览器没有做任何其他事情。