JavaScript变量不随XMLHttpRequest更改

时间:2015-07-12 21:40:08

标签: javascript xmlhttprequest

我试图运行它,但它不起作用。 它旨在返回在函数内部分配的变量,该变量作为回调传递给sendRequest(),它通过XMLHttpRequest异步地从Internet检索数据。

任何人都可以告诉我为什么这不起作用并且总是返回""?



function sendRequest(requestCode, args, callback){
	var req = requestEngineUrl + "?req=" + requestCode + ";" + args;
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function(){
		if(xmlHttp.readyState == 4)
		{	
			if(callback != null){
				callback(xmlHttp.responseText);
			}
		}
	};
	xmlHttp.open("GET", req, true);
	xmlHttp.send(null);
}






this.assembleProcess = function(){
		if(!isNull(this.id) && !isNull(this.titles)){
			var titles = this.titles;
			var id = this.id;
			c = "";
			sendRequest('304', id, 
				function(result){
					var res = result.split("/");
					var title = res[0];
					var possibilities = res[1];
					var fcontent = title + '<br><div>';
						if(titles.length != possibilities){
							console.log("WARNING: [SURVEYCARD].titles has not the same length as possibilities");
						}
					
						for(i = 0; i < possibilities; i++){
							fcontent += '<div><a onclick="sendRequest("301",' + id + ',' + i + ',null)">' + titles[i] + '</a></div>';
						}
					
					fcontent += '</div>';
					c = fcontent;
				});
			return c;
		} 
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

由于XMLHttpRequest是异步的,你应该写一个异步函数,就像这样

this.assembleProcess = function(callback){
        if(!isNull(this.id) && !isNull(this.titles)){
            var titles = this.titles;
            var id = this.id;
            c = "";
            sendRequest('304', id, 
                function(result){
                    var res = result.split("/");
                    var title = res[0];
                    var possibilities = res[1];
                    var fcontent = title + '<br><div>';
                        if(titles.length != possibilities){
                            console.log("WARNING: [SURVEYCARD].titles has not the same length as possibilities");
                        }

                        for(i = 0; i < possibilities; i++){
                            fcontent += '<div><a onclick="sendRequest("301",' + id + ',' + i + ',null)">' + titles[i] + '</a></div>';
                        }

                    fcontent += '</div>';
                    c = fcontent;
                    callback(c)
                });
        } 

然后,不应将this.assembleProcess用作结果函数,而应将函数作为参数传递:

而不是

console.log(this.assembleProcess);

这样做

this.assembleProcess(function(c){console.log(c)});