[英]Storing variable from ajax
我試圖從調用PHP腳本的ajax get請求存儲變量。 我需要將信息存儲在其中的變量以保留在區間函數中。 我看到了數據,並且在PHP腳本上調用成功,但是當我返回到包含ajax請求的代碼時,該變量未定義。 所以我的問題是我該如何將這些數據存儲到變量中並確保在離開網頁之前保留變量數據?
index.php
// ajax repeated call on home page
<script type="text/javascript">
var storedVariable0;
$(document).ready(function()
{
setInterval(function ()
{
// ensure data was retained will be undefined first time through
document.write(storedVariable0);
$.ajax({
url: '/fetchdatabase.php',
type: 'GET',
dataType: 'json',
})
.done(function(json){
storedVariable0 = JSON.stringify(json);
document.write(storedVariable0);
});
// ensure data is retained outside of the scope of the ajax call
document.write(storedVariable0);
}, 1000 ); //update every second
});
</script>
fetchdatabase.php
$sql = "SELECT content FROM messages ORDER BY id DESC LIMIT 1";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0)
{
// output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo json_encode($row);
}
}
謝謝你的幫助
默認情況下,Ajax是異步的。 (同步已棄用)。
通過異步,這意味着您的document.write(storedVariable0)的第三個塊很可能會在Ajax done塊之前執行。 因此,在完成之前,您將變得不確定。
建議執行wau異步操作,並且您需要更改編碼方式,並確保在完成操作后所有對storedVatiable0的訪問均已發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.