Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在jQuery中设置全局变量_Jquery - Fatal编程技术网

在jQuery中设置全局变量

在jQuery中设置全局变量,jquery,Jquery,如何设置全局变量 $(document).ready(function() { $("a.action").click(function(event) { var tempResponse = ""; $.get("", function(response){ tempResponse = response; }); alert("response "

如何设置全局变量

$(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
});
我声明了globa变量
tempResponse
。我设置了获取回拨功能

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

但这对我来说是行不通的


为什么会发生这种情况?

因为您在实际设置变量之前调用了警报。请记住,调用
$时正在执行异步查询。get
。请尝试以下方法:

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

您只是在$get之后立即调用警报,因此tempResponse尚未准备就绪,无法使其正常工作:

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

请注意,您的警报现在位于json回调函数中;此函数在json查询完成之前不会执行

我的建议是您必须等待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.');
  }
});

我相信在脚本的顶部设置全局变量,然后将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);
在返回“response”的脚本中,确保其为json格式。在php中,我会将数据放入如下数组中

$json_data = array('response'=>$var_name_php_for_response_value);
然后只回显所需的数据,如下所示:

 json_encode($json_data);

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

我想在$.get函数范围之外使用响应。我只是使用alert来简化代码。你还有别的建议吗?没有别的建议了。您不能使用尚未分配的内容。您仍然可以使用全局变量分配其值,但不能在
$函数之后立即使用它。get
函数。当锚链接单击$(“a.action”)时,此脚本调用。单击(函数(事件){var tempResponse=”“;//依此类推}我想在$.get函数范围之外使用响应。我只是使用alert来简化我的代码。你还有其他建议吗?很好,我需要这个解决方案!