在jQuery中设置全局变量

时间:2010-01-23 11:52:31

标签: jquery

如何设置全局变量。

$(document).ready(function() {

      $("a.action").click(function(event) {
            var tempResponse = "";
            $.get("", function(response){
                tempResponse = response; 
            });
            alert("response " + tempResponse );
      }

       //todo use response to manipulate some data
});

我宣布了全局变量tempResponse。我设置了回调函数。

tempResponse = response; 

但是当我尝试提醒响应时,没有显示任何数据。我也尝试这个解决方案。我改变了变量声明 变为$.tempResponse并将设置的脚本更改为$.tempResponse = response;

但它无效。

为什么会发生这种情况?

5 个答案:

答案 0 :(得分:3)

我相信将全局变量设置在脚本的顶部,然后将ajax调用设置为async:false将完全满足需要。

这样ajax在javascript尝试分配变量之前就完成了。 另外,ajax函数对我来说比使用.get。

更干净
tempResponse = null;
$.ajax({
    url: 'whatever.cgi',
    async: false,
    dataType: 'json',
    data: { blank: null }
    success: function(data) {
         tempResponse = data.response;
    }
 }).error(function(){
    alert('Ajax failed')
 });

 alert(tempResponse);

在返回“响应”的脚本中,请确保它采用json格式。在php中我会将数据转换为像

这样的数组
$json_data = array('response'=>$var_name_php_for_response_value);

然后只回显所需的数据:

 json_encode($json_data);

这将生成格式:{ "response":"some response text" },这是正确的json格式。

答案 1 :(得分:2)

因为您在实际设置变量之前调用警报。请记住,当您致电$.get时,您正在执行异步查询。试试这个:

$(document).ready(function() {
    $.get('/somescript.cgi', function(response){
        alert('response ' + response);
    });
});

答案 2 :(得分:0)

您只是在$ .get之后立即调用警报,因此tempResponse尚未准备就绪

答案 3 :(得分:0)

使其有效:

$(document).ready(function() {
    var tempResponse = "";
    $.get("", function(response){
        tempResponse = response; 
        alert("response " + tempResponse );
    });
});

注意你的警报现在在json回调函数内;在json查询完成之前,此函数不会执行

答案 4 :(得分:0)

我的建议是你必须等待ajax完成。 使用ajaxComplete()

如果你有:

var tempResponse = "";
    $.get("ajax/test.html", function(response){
        tempResponse = response; 

    });
你可以:

$('.log').ajaxComplete(function(e, xhr, settings) {
  if (settings.url == 'ajax/test.html') {
    alert("response " + tempResponse );
    $(this).text('Triggered ajaxComplete handler.');
  }
});
相关问题