使用 XMLHttpRequest 将代码片段提交到数据库

Submitting code snippets to database using XMLHttpRequest

在我的网站中,我使用 XMLHttpRequest 将数据发送到数据库。我尝试提交代码片段和简单的西班牙语字符,但是当我检查收到的数据时,我只看到这些代码片段或字符之后的内容,如下所示:

发送的数据: 你好<?xml version="1.0" encoding="utf-8"?>

收到的数据: 你好

那么,有什么方法可以使用 XMLHttpRequest 提交代码片段或特殊字符吗?如果没有,那除了php?

之外最好的方法是什么?

这是我的 XMLHttpRequest 代码:

    //call the function for the XMLHttpRequest instance
    //create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
    var xmlHttp;
    if(window.XMLHttpRequest) {//for Forefox, IE7+, Opera, Safari, ...
        xmlHttp = new XMLHttpRequest();
    }else if(window.ActiveXObject) {//for Internet Explorer 5 or 6
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    //create pairs index=value with data that must be sent to server
    var data = "title="+title+"&desc="+desc;

    //sets the request
    xmlHttp.open("POST","http://mywebsite.com/database.php",true);          

    //adds a header to tell the PHP script to recognize the data as is sent via POST
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    //sends the request
    xmlHttp.send(data);

    //Check request status
    //If the response is received completely, will be transferred to the HTML tag with tagID
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            document.getElementById("div").innerHTML=xmlHttp_refresh_es_ES.responseText;
        }
    }

始终在发送数据之前对其进行编码,这样空格和特殊字符就不会成为问题(只要它是 UFT8)

var data = "title=" + encodeURIComponent(title) + "&desc=" + encodeURIComponent(desc);