函数内部 Ajax 成功 - Cordova/Framework7

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。将您的函数从 onDeviceReady 函数中移出。

例子

在这里你会看到innerFunctioninnerVariableundefined,因为它们在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中scope的详细描述:What is the scope of variables in JavaScript?