繁体   English   中英

将 JSON 数据发送到 MySQL 数据库?

[英]Send JSON data to MySQL database?

我需要将 JSON 数据发送到 MySQL 数据库,但是当我尝试执行此操作时,我的代码仅将“{“0”:“A”发送到 MySQL 数据库。

这是我的代码:

JavaScript

<span id="start_button_container">Send and start</span>

const allCards = {
    '0':'A &#9830;','1':'A &#9829;','2':'A &#9827;','3':'A &#9824;',
    '4':'10 &#9830;','5':'10 &#9829;','6':'10 &#9827;','7':'10 &#9824;',
    '8':'K &#9830;','9':'K &#9829;','10':'K &#9827;','11':'K &#9824;',
    '12':'Q &#9830;','13':'Q &#9829;','14':'Q &#9827;','15':'Q &#9824;',
    '16':'J &#9830;','17':'J &#9829;','18':'J &#9827;','19':'J &#9824;'
};

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);
        }
    }
}

我究竟做错了什么?

encodeURIComponent() function 对我帮助很大:

let data = JSON.stringify(encodeURIComponent(allCards));

如果您/某人仍想知道为什么会发生这种情况,则每个与号 (&) 都是查询字符串中的新输入。 含义var1=value&var2=value&var3=value 您的 JSON 包含与号,因此解析器认为您正在启动一个新变量。

var1=value&var2={"a":"&2934;"}
                      ^ This one starts a new variable

var2 包含{"a":"1 and processes 2934;"}作为新变量名。

encodeURIComponent对 & 符号进行转义,因此查询字符串解析器不使用它来划分变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM