function get_request(url) {
var request = new getXMLObject();
request.onreadystatechange = function () {
if (request.readyState == 4) {
alert(request.responseText);
var data = eval('(' + request.responseText + ')');
alert(data);
return data;
}
}
request.open("GET", url, true);
//alert(document.getElementById('energy').innerHTML);
request.send();
}
function loadjobs() {
var url = "loadjobs.php?tab=1&id=1111";
//var data=
//alert(check());
alert(get_request(url));
//alert(data);
}
当我获取json格式的数据时,我在alert(get_request(url));
中获取NULL
,而在alert(data);
中获取数据。
帮帮我
发布于 2010-07-07 16:46:23
这是因为请求是异步的。get_request(url)
函数返回任何内容,因此返回null (尽管我认为它应该是未定义的,并且不是null )。
稍后,当AJAX请求完成并从服务器返回数据时,将调用onreadystatechange
函数,因此那里的警报有效。
发布于 2010-07-07 16:45:15
这是对AJAX工作原理的误解。Ajax是异步的。在loadjobs()
之后将调用onreadystatechange
函数。您指定的“返回路径”永远不会起作用。get_request()
永远不能返回获取的值。
您有两个选择。或者使脚本同步-这是可以做到的,但不建议这样做,因为它会冻结浏览器。
或者,更好的做法是在onreadystatechange
回调中处理所有需要做的事情。
发布于 2010-07-07 16:45:55
问题是Ajax请求使用asynchronously.所以你不能马上返回数据。应该这样做的方法是指定一个回调函数,该函数将处理响应数据。
function handleJSON( data ) {
// ...
// do whatever you want to do with the data
}
ajax( "url/file.php?param=value", handleJSON );
////////////////////////////////////////////////////////////////////////////////
function getXmlHttpObject() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function ajax(url, onSuccess, onError) {
var xmlHttp = getXmlHttpObject();
xmlHttp.onreadystatechange = function () {
if (this.readyState == 4) {
// onError
if (this.status != 200) {
if (typeof onError == 'function') {
onError(this.responseText);
}
}
// onSuccess
else if (typeof onSuccess == 'function') {
onSuccess(this.responseText);
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return xmlHttp;
}
https://stackoverflow.com/questions/3193182
复制相似问题