我需要將 JSON 數據發送到 MySQL 數據庫,但是當我嘗試執行此操作時,我的代碼僅將 "{"0":"A" 發送到 MySQL 數據庫。這是我的代碼:JavaScript<span id="start_button_container">Send and start</span>const allCards = { '0':'A ♦','1':'A ♥','2':'A ♣','3':'A ♠', '4':'10 ♦','5':'10 ♥','6':'10 ♣','7':'10 ♠', '8':'K ♦','9':'K ♥','10':'K ♣','11':'K ♠', '12':'Q ♦','13':'Q ♥','14':'Q ♣','15':'Q ♠', '16':'J ♦','17':'J ♥','18':'J ♣','19':'J ♠'};let userInTable = localStorage.getItem( 'saved_user' );if (userInTable) { // Save user and find table onclick START saveUser.style.display = 'none'; hello.textContent = "Hi " + userInTable; start.onclick = () => { if (userInTable) { let x = new XMLHttpRequest(); let url = "php/findtable.php"; let data = JSON.stringify(allCards); let params = "cards="+data+"&user="+userInTable; x.open("POST", url); x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); x.send(params); x.onreadystatechange = () => { if (x.readyState == 4 && x.status == 200) { console.log(x.responseText); } } } }}這是我的 PHP 代碼:if (isset($_POST["cards"],$_POST["user"])) { $cards = $_POST["cards"]; $user = $_POST["user"]; $query = "INSERT INTO tables (u_1,all_cards) VALUES (?,?)"; if ($stmt = $conn->prepare($query)) { $stmt->bind_param("ss", $user, $cards); if ($stmt->execute()) { print_r($cards); } }}我究竟做錯了什么?
2 回答

慕沐林林
TA貢獻2016條經驗 獲得超9個贊
encodeURIComponent() 函數對我幫助很大:
let data = JSON.stringify(encodeURIComponent(allCards));

MM們
TA貢獻1886條經驗 獲得超2個贊
如果您/某人仍然想知道為什么會發生這種情況,則每個與號 (&) 都是查詢字符串中的新輸入。意思是var1=value&var2=value&var3=value
。您的 JSON 包含&符號,因此解析器認為您正在開始一個新變量。
var1=value&var2={"a":"&2934;"} ^ This one starts a new variable
var2 包含{"a":"1
并2934;"}
作為新變量名進行處理。
encodeURIComponent
對 & 符號進行轉義,因此查詢字符串解析器不會使用它來進行變量劃分。
- 2 回答
- 0 關注
- 137 瀏覽
添加回答
舉報
0/150
提交
取消