不能在相同的html页面上使用来自JS的全局变量和其他脚本元素中的AJAX调用

时间:2022-12-08 11:10:08

I've been looking around as to how to use a variable from one script on a page and use it in another script. I've found that you can set your variable to global (although this is not preferred, but I havn't found a better way).

我一直在研究如何在页面上使用一个脚本中的变量,并在另一个脚本中使用它。我发现您可以将变量设置为全局变量(尽管这不是首选,但我没有找到更好的方法)。

I am using the Bootstrap framework.

我正在使用引导框架。

On my page, I have an AJAX call in a function. I have declared the variable in front on the function so that it is a global variable. The value of the variable is set in the success function of the AJAX call.

在我的页面上,我有一个函数的AJAX调用。我在函数前面声明了变量,使它成为全局变量。变量的值在AJAX调用的success函数中设置。

In another script (inside a modal) I then use the variable to output as text. This works when I set the value of the variable outside the AJAX function, but it gives value='undefined' when the value is set in the AJAX success.

在另一个脚本(在模态中)中,我使用变量作为文本输出。当我在AJAX函数之外设置变量的值时,这是可行的,但是在AJAX成功中设置值时,它会给出value='undefined'。

The modal in which the variable is used is only opened after the AJAX success function, but maybe the value is already read before the AJAX request, even when the modal is not shown? Is there a way to say that it only has to be loaded after the AJAX success function?

使用该变量的模态仅在AJAX success函数之后打开,但即使没有显示模态,也可能在AJAX请求之前已经读取了该值?有没有一种方法可以说明它只需要在AJAX成功函数之后加载?

This is an abstract of my code for the AJAX function:

这是我的AJAX函数代码的摘要:

<script type="text/javascript">
var theVariable;
function() {
    //AJAX Call
    $.ajax({
        //Abbreviated
        success: function(data) {
            theVariable = "test";
        }
    });
}

Here is the code I use in the modal to read the variable

这是我在模式中用来读取变量的代码

<p id="demo"></p>
<script>
     document.getElementById("demo").innerHTML = theVariable;
</script> 

So to recap, when I set the value of theVariable while declaring it (outside of the AJAX function), the value is displayed in the modal. However, when I try to set the value inside the AJAX success function this value is undefined.

因此,总结一下,当我在声明变量时(在AJAX函数之外)设置变量值时,该值将显示在模态中。但是,当我尝试在AJAX success函数中设置值时,这个值没有定义。

1 个解决方案

#1


2  

It happens because theVariable is outside the scope of $.ajax().

之所以会出现这种情况,是因为该变量不在$.ajax()的范围之内。

This should work:

这应该工作:

var theVariable;
function() {
    var that = this;
    //AJAX Call
    $.ajax({
        //Abbreviated
        success: function(data) {
            that.theVariable = "test";
        }
    });
}

#1


2  

It happens because theVariable is outside the scope of $.ajax().

之所以会出现这种情况,是因为该变量不在$.ajax()的范围之内。

This should work:

这应该工作:

var theVariable;
function() {
    var that = this;
    //AJAX Call
    $.ajax({
        //Abbreviated
        success: function(data) {
            that.theVariable = "test";
        }
    });
}