我想从 JSON 获取一个值并在 Ajax 请求内的函数中使用:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert('device ready');
function Hi(img_url){
alert('Hi, the img_url is '+img_url);
}
}
ajax请求:
$$.ajax({
type: "GET",
dataType: 'json',
url: target,
//Sucess
success: function(data){
var img_url = data.media.display_src;
Hi(img_url);
},
//Error
error: function(xhr,status){
alert("Error"+status+xhr);
console.log(xhr.response);
}
});
但是函数 Hi()
始终是“未定义”...出了什么问题?
谢谢
最佳答案
因为您的 Hi
函数位于另一个范围内。每个函数
都会创建它的自己的作用域,因此在该作用域
中定义的内容对于另一个函数来说是未定义
。将您的函数从 onDeviceReady
函数中移出。
示例
在这里您将看到innerFunction
和innerVariable
是未定义
,因为它们在outer
外部不可见功能。
function outer(){
var innerVariable = 'hello';
function innerFunction(){
console.log('inner function') ;
}
}
console.log(innerVariable);
innerFunction();
关于javascript - Ajax 中的函数成功 - Cordova/Framework7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42044329/