[英]How do I ensure a PHP variable is available in index.php after being changed in a second php file (via a jQuery load())?
在我的index.php
我有以下 jQuery 代碼用於響應單擊圖像:
<script>
$(document).on('click',".i-give-up", function() {
$("#take-a-guess").load("get_snippet.php");
[...snip...]
generate_HSK2_circle(<?php echo $answer_data["HSK2level"]; ?>);
});
</script>
當我單擊圖像時,它會加載執行和處理 MySQL 查詢的get_snippet.php
。 此外,如果我添加
echo "<script>console.log('get_snippet[new] HSK2 level: " . $answer_data["HSK2level"] . "' );</script>";
到年底get_snippet.php
,我可以看到正確的變量$answer_data["HSK2level"]
在get_snippet.php
。
問題是index.php
中的變量$answer_data["HSK2level"]
不會因為加載get_snippet.php
而改變。
問題:在第二個 php 文件(通過 jQuery load())中更改后,如何確保 index.php 中的 PHP 變量可用?
index.php
文件在呈現后不會更改,除非在服務器上處理 PHP。
為了傳遞這些數據,您可能需要考慮使用查詢字符串並使用 get 變量重定向回 index.php。
https://www.php.net/manual/en/reserved.variables.get
然后在您的get_snippet.php
,您將指向index.php?answer=...
並通過htmlspecialchars($_GET["answer"])
檢索它
在我看來,您實際上是想將$answer_data["HSK2level"]
的 php 值存儲在一個 javascript 變量中,因此每次調用generate_HSK2_circle()
您都會傳入最新的值
請注意,ajax 也是異步的,因此您需要在繼續處理新數據之前使用完整的回調
為此,您的 js 將如下所示:
<script>
// new js variable recieves value on page load from php
var answer_data = <?php echo $answer_data["HSK2level"]; ?>;
$(document).on('click',".i-give-up", function() {
// use complete callback of load to assure new data loaded
$("#take-a-guess").load("get_snippet.php", function(){
// new data has loaded
[...snip...]
// use the js variable in function call
generate_HSK2_circle(answer_data);
});
});
</script>
然后在你的新腳本標簽(來自加載)中更新那個 js 變量值
echo "<script>answer_data=". $answer_data['HSK2level']. "</script>";
如果這個新的腳本標簽是load()
從服務器發送的唯一數據,更合適的方法是發送 json 並使用$.getJSON
並從響應對象手動更新 js 變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.