简体   繁体   English

使用来自Ajax响应的变量

[英]Use variable from Ajax response

I have two files: 我有两个文件:

example.html: 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: example1.html的:

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

In example.html , I need console.log(alpha) to output "data". example.html中 ,我需要console.log(alpha)来输出“数据”。 I make an Ajax request to example1.html , and update the contents of my div with the returned html. 我向example1.html发出Ajax请求,并使用返回的html更新div的内容。 The constant alpha isn't useable until new Dropzone() succeeds. 直到new Dropzone()成功,常量alpha new Dropzone() How can I make this code work? 如何使此代码起作用?

One option is to make your alpha variable global. 一种选择是使您的alpha变量成为全局变量。

You declared your alpha variable inside success function so you can only use that variable inside it. 您在成功函数中声明了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>

Now you can access it as 现在您可以以

$(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