簡體   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