[英]Function inside Ajax success - Cordova/Framework7
我想從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()
始終是'undefined'...怎么了?
謝謝
因為您的Hi
函數在另一個作用域內。 每個function
創建自己的作用域 ,因此在該scope
undefined
對於另一個功能是undefined
的。 將函數從onDeviceReady
函數onDeviceReady
。
例
在這里,您將看到innerFunction
和innerVariable
是undefined
,因為它們在outer
函數外部不可見。
function outer(){ var innerVariable = 'hello'; function innerFunction(){ console.log('inner function') ; } } console.log(innerVariable); innerFunction();
只需在onDeviceReady()
函數外部定義Hi()
。
document.addEventListener("deviceready", onDeviceReady, false);
function Hi(img_url){
alert('Hi, the img_url is '+img_url);
}
function onDeviceReady() {
alert('device ready');
}
在javascript中,您不能在定義的范圍之外使用函數。 這是JS中作用域的詳細說明: JavaScript中變量的作用域是什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.