繁体   English   中英

使用来自Ajax响应的变量

[英]Use variable from Ajax response

我有两个文件:

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 new Dropzone() 如何使此代码起作用?

一种选择是使您的alpha变量成为全局变量。

您在成功函数中声明了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", 
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM