为什么在ajax调用中编码的特殊字符显示为不同的特殊字符?

时间:2014-06-11 01:05:55

标签: php ajax character-encoding

在我网站上的一个用户输入中,用户可以输入字母数字+特殊字符的字符串。在用户输入数据后,单击按钮会调用一个看起来基本如下的ajax函数:

    function ajaxEZ(id, x) {
    var ajaxRequest, param;
    try {
        ajaxRequest = new XMLHttpRequest();
    } catch (e1) {
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e2) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e3) {
                alert("Your browser broke!");
                return false;
            }
        }
    }
    ajaxRequest.onreadystatechange = function () {
        if (ajaxRequest.readyState === 4) document.getElementById(id).innerHTML = ajaxRequest.responseText;
    };
    param = encodeURIComponent(x);
    ajaxRequest.open("GET", "AJAX_file.php?param=" + param, true);
    ajaxRequest.send(null);
}

encodeURIComponent(x)适用于&等特殊情况。目前,我正在测试5i√2的用户输入( 5i√2 )。输入被发送到php文件,该文件将字符串与其中一个数据库表中存在的“正确”答案进行比较。

问题是即使编码的字符串被解码,这个特定的字符串5i√2也会存储在相应的表中:

5i√2

我尝试在我的php文件中解码字符串:

<?php include 'connect.php';

$UserAnswer = $_GET['param'];
$UserAnswer1 = urldecode($UserAnswer);
$sql = mysqli_query($cxn, "INSERT INTO myTable (answer) VALUES ('$UserAnswer1')");

但是,该字符串仍然存储在数据库中:

5i√2    (This is the same result whether or not the urldecode is present)

对于表 myTable ,排序规则为:latin1_swedish_ci

我希望存储的字符串为 5i&radic;2

请注意,作为辅助问题,存储为 5i&radic;2 的正确答案不会与用户输入进行“等效”比较,即使用户输入为 {{ 1}}

但是,如果正确答案存储为 5i%E2%88%9A2 ,并且用户输入也 5i%E2%88%9A2 强>

有人可以详细了解发生了什么事吗?为什么php解码的字符串(urldecode($ UserAnswer))没有被正确解码并最终存储为5iâš2?另请注意,我的HTML字符集是utf-8

1 个答案:

答案 0 :(得分:1)

GET参数已经解码,因此您要对其进行两次解码。你应该删除:

$UserAnswer1 = urldecode($UserAnswer);

除此之外,您可能会收到一个字符,因此如果您想在将其存储到数据库之前对其进行编码,则应使用htmlentities()代替:

$UserAnswer1 = htmlentities($UserAnswer);

虽然我会为所有事情亲自去找utf8。

您还应该使用预准备语句来避免sql注入。