尝试使用带有.ajax调用的回调来为变量赋值

时间:2014-01-10 16:08:30

标签: javascript jquery ajax callback

我正在尝试使用.ajax调用,将xml文档中的值分配给javascript中的变量。我无法弄清楚如何使用回调,我知道这个话题在论坛上得到了很好的讨论,但是我还没有找到一个能够做我想做的事情的例子。下面的示例调用Google地图,然后返回“中央标准时间”字符串。我可以使用.ajax调用将文本移动到div。但我无法弄清楚如何将其分配给变量my_zone,并将该值移动到div。

有人能帮帮我吗?请?如果有人可以在这里重写代码,谢谢......

<!DOCTYPE html>
<html>
<head>

<script type='text/javascript' src='//code.jquery.com/jquery-2.0.2.js'></script>


<script type='text/javascript'>
$(document).ready(function(){ 

  //this works great, we get the value and it goes to the 'zzz' div, asynchronously
  $.ajax({
 type: "GET",
 url: "https://maps.googleapis.com/maps/api/timezone/xml",
 data: {
            location: '35.129186,-89.970787',
            timestamp: '1389006000',
            sensor: 'false'
        }, 
 dataType: "xml",    
 success: function(xml) {
   var val = $(xml).find('time_zone_name').text();    
   $( "#zzz" ).empty().append( val );  //want to return val  
 }
  });  

  //this is what I am trying to do, get the return'd value, and put it into a variable
  var my_zone = getZone();     //just want to get the value into a variable
  $("#xxx").empty().append(my_zone);   //do something with it, maybe display it          

  function getZone() {
 $.ajax({
   type: "GET",
   url: "https://maps.googleapis.com/maps/api/timezone/xml",
   data: {
   location: '35.129186,-89.970787',
   timestamp: '1389006000',
   sensor: 'false'
   }, 
   dataType: "xml",    
   success: function(xml) {
 var val = $(xml).find('time_zone_name').text();    
 console.log(val);
 return val;  //needs to be part of a Callback 
   }
 });     
  }
  ///////////

});
</script>

</head>
<body>
<div id="xxx">some output here....</div>
<div id="zzz">some output here....</div>

</body>

</html>

1 个答案:

答案 0 :(得分:1)

您不能这样做,而是可以将回调函数传递给getZone(),一旦使用所需参数完成请求,就会调用该函数

//pass a callback function which will get called when the ajax request is completed
getZone(function (my_zone) {
    $("#xxx").empty().append(my_zone); //do something with it, maybe display it          
});

function getZone(callback) {
    $.ajax({
        type: "GET",
        url: "https://maps.googleapis.com/maps/api/timezone/xml",
        data: {
            location: '35.129186,-89.970787',
            timestamp: '1389006000',
            sensor: 'false'
        },
        dataType: "xml",
        success: function (xml) {
            var val = $(xml).find('time_zone_name').text();
            console.log(val);
            callback(val); //call the callback with the value
        }
    });
}