javascript - 使用 Ajax 响应中的变量

标签 javascript jquery ajax

我有两个文件:

example.html:

<div class="my-div"></div>
<script type="text/javascript">
$(document).ready(function() {
    $.ajax({
        url: "example1.html",
        type: "get",
        success: function(response) {
            $(".my-div").html(response);
        }
    });

    $(document).on("click", "button", function() {
        console.log(alpha); // Should print "data", 
    });
});
</script>

example1.html:

<button></button>
<script type="text/javascript">
$(document).ready(function() {
    var myDropzone = new Dropzone("", {
        success: function(file, response) {
            const alpha = "data";
        }
    });
});
</script>

example.html中,我需要console.log(alpha)来输出“数据”。我向 example1.html 发出 Ajax 请求,并使用返回的 html 更新 div 的内容。在 new Dropzone() 成功之前,常量 alpha 不可用。我怎样才能让这段代码工作?

最佳答案

一种选择是将您的 alpha 变量设置为全局变量。

您在 success 函数中声明了 alpha 变量,因此您只能在其中使用该变量。

<button></button>
<script type="text/javascript">
const alpha; /* Init it here */

$(document).ready(function() {
    var myDropzone = new Dropzone("", {
        success: function(file, response) {
            alpha = "data"; /* Assign the value here */
        }
    });
});
</script>

现在您可以通过以下方式访问它

$(document).on("click", "button", function() {
    console.log(alpha); // Should print "data", 
});

关于javascript - 使用 Ajax 响应中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48555378/

相关文章:

javascript - 使用脚本而不是平板电脑检测手机

javascript - jQuery 复选框错误

javascript - 相当于纯 JS 中 jQuery 的 content().find() 链式方法

javascript - 无需 JSONP 或 CORS 即可获取跨域 XML 文件

javascript - getElementById() 对于现有对象返回 Null

javascript - 为什么 Javascript "class"实现会用同名函数声明覆盖类名?

javascript - 数据表未捕获类型错误

jquery - 在一页中使用 2 个 jquery 第二个 jquery ul 和 li 类和样式得到改变

java - 将复杂的 json 对象发送到 Spring MVC Controller

jquery - 未捕获的类型错误 : Cannot read property 'getJSON' of undefined