函数中的变量
Variables in functions
问题出在变量和函数返回。此代码有助于连接到 mysql 数据库并选择两个城市之间的距离。可变ret_pomoc
是距离。
ret_pomoc
中的值我需要在另一个函数中使用,例如在 another_fuction()
中。
这是代码:
var ret_pomoc;
var vzdialenost;
function ajaxFunction(mesto_1,mesto_2){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('mapa2');
ajaxDisplay.value = ajaxRequest.responseText;
ret_pomoc=ajaxDisplay.value; //HERE IS KEY VARIABLE
console.log(ret_pomoc); // 1. Here it is OK show 91
}
}
console.log(ret_pomoc); // 2. Here it does not work show undefined and return does not work
// Now get the value from user and pass it to
// server script.
var z_mesta = mesto_1;
var do_mesta = mesto_2;
var queryString = "?z_mesta=" + z_mesta ;
queryString += "&do_mesta=" + do_mesta;
ajaxRequest.open("GET", "pristup.php" +
queryString, true);
ajaxRequest.send(null);
}
我需要在ahother函数中使用ret_pomoc
的值
function another_function(){
vzdialenost=ajaxFunction('Bratislava','Nitra') + ajaxFunction('Poprad','Nitra') ;
}
ajax 请求异步工作,因此执行此操作的方法是传递一个 callback
函数,该函数将在响应返回时调用。
了解 Javascript 中的回调函数
function some_function2(url, callback) {
var httpRequest; // create our XMLHttpRequest object
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Internet Explorer is stupid
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() {
// inline function to check the status
// of our request
// this is called on every state change
if (httpRequest.readyState === 4 &&
httpRequest.status === 200) {
callback.call(httpRequest.responseXML);
// call the callback function
}
};
httpRequest.open('GET', url);
httpRequest.send();
}
// call the function
some_function2("text.xml", function() {
console.log(this);
});
console.log("this will run before the above callback");
相关文章:
- 带有两个变量函数的Ajax提交表单
- 设置变量函数不起作用
- 为什么使用 ||在变量函数声明中
- Javascript 变量函数不保留值
- 为什么要在函数定义之外引用静态变量(函数属性)
- jQuery 变量函数无法运行
- 循环中的变量函数定义
- javascript onclick设置为变量函数名
- JavaScript:调用已启动类(数据包处理程序)的变量函数
- Javascript测试存根全局变量函数
- Aptana能否识别其他文件中定义的变量/函数
- jquery将其传递给变量函数
- 传递一个变量函数到数组[Javascript]
- 如何使用' this '像一个对象,并通过字符串获得它的变量/函数
- javascript变量/函数的首字母是什么意思?
- Javascript .apply带有变量函数名
- 在JavaScript中添加一个全局变量/函数(特别是NativeScript)
- 变量函数未定义错误
- AngularJS-继续检查变量/函数
- Javascript从本地向全局变量函数添加行