我需要在第二个函数中使用来自第一个函数(变量url)的变量生成值,这里是一个代码:
var kategorije = ["c1", "c2", "c3", "c4", "c5", "c6"];
var url;
function checkbox_test() { //first function
// calculating url ...
alert(url); // here everything is ok, something like c1=x&c2=a&c3=5 ...
}
function loadXMLDoc() { // second function
regid = "123456abcdefg";
var xmlhttp;
xmlhttp=new XMLHttpRequest()
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.example.com/?regId=" + regid + '&' + url, true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
alert(url); // just checking is value of url is correct! here it say url is undefined!
}
我需要将在GET中的第一个函数中生成的url值作为url传递。谢谢!
答案 0 :(得分:0)
您必须在第二个功能之前致电checkbox_test()
,并在var url
checkbox_test()
之后将return
分配给url
的输出:
var kategorije = ["c1", "c2", "c3", "c4", "c5", "c6"];
var url;
function checkbox_test() { //first function
// calculating url ...
alert(url); // here everything is ok, something like c1=x&c2=a&c3=5 ...
return url
}
url = checkbox_test();
loadXMLDoc(url);
function loadXMLDoc(url) { // second function
regid = "123456abcdefg";
var xmlhttp;
xmlhttp=new XMLHttpRequest()
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.example.com/?regId=" + regid + '&' + url, true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
alert(url); // just checking is value of url is correct! here it say url is undefined!
}
答案 1 :(得分:0)
除了上面的建议,你可以尝试使用'回调',线程here有一些很好的贡献和例子。
因此,在您的上下文中,您可以使用这样的回调,
function checkbox_test( callback ) {
// do calculation and when 'url' is available,
// invoke callback (which is loadXMLDoc())
callback( url );
}
function loadXMLDoc( aValuePassedFrom_checkbox_test ) {
// do stuffs with value (url)
}
// call function checkbox_test, passing in callback fn
checkbox_test( loadXMLDoc );
希望这有帮助。