我需要將 JSON 數(shù)據(jù)發(fā)送到 MySQL 數(shù)據(jù)庫(kù),但是當(dāng)我嘗試執(zhí)行此操作時(shí),我的代碼僅將 "{"0":"A" 發(fā)送到 MySQL 數(shù)據(jù)庫(kù)。這是我的代碼: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); } }}我究竟做錯(cuò)了什么?
2 回答

慕沐林林
TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
encodeURIComponent() 函數(shù)對(duì)我?guī)椭艽螅?/p>
let data = JSON.stringify(encodeURIComponent(allCards));

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