0

私は 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!"ますか?

4

1 に答える 1

3

上記のコードが機能しない理由は、spike.xhr.connect関数が非同期であるためです。つまり、ブラウザーにリクエストを送信するように指示できますが、ブラウザーが応答が返されるのを待っている間、他の処理を続行できます。

JavaScript は単一のスレッドで実行されます。つまり、一度に 1 つのことしか実行できません。「AJAX」呼び出しなどの特定の操作は、ブラウザーがその要求を行う方法を知っているという点で非同期ですが、現在実行中のコードが要求を待機することをブロックしません。通常、非同期コードは、リクエストが返されたときに実行されるコールバック関数で呼び出されます。

// pseudo code.

spike.xhr.connect( 'http://google.com', function ( response ) {
    alert( 'google' );
});
alert( 'this will fire before spike.xhr.connects callback' );

コールバック関数は、サーバーからの応答が返され、ブラウザが他に何もしていないときに実行ます

于 2012-06-05T15:16:27.247 に答える