2013-04-26 2 views
0

В настоящее время я пытаюсь получить возвращаемое значение JS, и я действительно не знаю Резон, почему это не работает ...Получить JS значения функции

Привет HOPER мой код является наиболее простым для чтения , как это возможно, заранее спасибо:

<script type="text/javascript"> 
       function getValLocalSto(key, URL){ 
        console.log(key); 
        console.log(URL); 
        var myKey = localStorage.getItem(key); 

        if(myKey == null){ 

         // getting back JSON data 

          $.ajax({ 
           url: URL, 
           dataType: 'json', 
           async: false, 
           success: function (json) { 
              var test; 
              console.log(JSON.stringify(json)); // the result is a well formed JSON string 
              localStorage.setItem(key,JSON.stringify(json)); 
              myKey = localStorage.getItem(key); 
              test =jQuery.parseJSON(myKey); 
              console.log("My function result : "+test); // the result is a [object Object] 
              return test; 
             } 


          }); 
        }else { 
         // Other work whatever 
          } 

       } 

       //call my function 
        console.log("sortie fonction : "+getValLocalSto("testJson", "do/profil")); // the result is "undefined" 
        var myuResult = getValLocalSto("testJson", "do/profil")); // the result is "undefined" 
        console.log(ff.prenom); 
        document.getElementById("myDiv").innerHTML="<div><input disabled='disabled' name='text-basic' id='text-basic' type= 'text' value='Votre nom "+ff.nom+"'/></div>"; 
        document.getElementById("myDiv").innerHTML+="<div> <input disabled='disabled' name='text-basic' id='text-basic' type= 'text' value= 'Votre prenom "+ff.prenom+"'/></div>"; 
     </script> 

Решение:

function getValLocalSto(key, URL){ 
        // do my stuff 
          }); 
        }else { 
         // Other work whatever 
          } 
        return test; 
       } 
+0

Вам нужно прочитать асинхронные основы в javascript. Короче говоря, вызов ajax еще не закончен, когда возвращается возвращаемое значение. – David

+0

Спасибо, я нашел решение и переделал свою статью. – Lombric

+0

- это контроль, достигающий метода успеха? –

ответ

0

Просто объявить переменную тест вне функции АЯКС успеха во внешней функции getValLocalSto воспользовавшись переменной области. Иначе вам понадобится обратный вызов, чтобы вернуть переменную из функции успеха ajax. Попробуйте следующее:

<script type="text/javascript"> 
       function getValLocalSto(key, URL){ 
        ... 

        if(myKey == null){ 

         // getting back JSON data 

         var test; 

         $.ajax({ 
           url: URL, 
           dataType: 'json', 
           async: false, 
           success: function (json) { 
              console.log(JSON.stringify(json)); // the result is a well formed JSON string 
              localStorage.setItem(key,JSON.stringify(json)); 
              myKey = localStorage.getItem(key); 
              test =jQuery.parseJSON(myKey); 
              console.log("My function result : "+test); // the result is a [object Object] 

             } 
         }); 

         return test; 

        }else { 
         // Other work whatever 
          } 

       } 

       //call my function 
        console.log("sortie fonction : "+getValLocalSto("testJson", "do/profil")); // the result is "undefined" 
        ... 
     </script> 
0

Вы можете передать обратный вызов AJAX. Изменить определение функции для:

function getValLocalSto(key, URL, callback){ 
... 
$.ajax({ 
url: URL, 
dataType: 'json', 
async: false, 
success: callback 
}); 
... 

в коде:

getValLocalSto("testJson", "do/profil", function(data) { 
    localStorage.setItem(key,JSON.stringify(data)); 
    myKey = localStorage.getItem(key); 
    test = jQuery.parseJSON(myKey); 
    // here you work with test as you want as a result of getValLocalSto 
}); 
Смежные вопросы