2015-04-20 74 views
0

在我的網站中,我使用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; 
     } 
    } 

回答

1

始終在發送之前編碼數據,這樣,空格和特殊字符不應該是一個問題(只要它是UFT8)

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

謝謝!!!!!!!!剛剛嘗試過,它工作!!!!!! – theappnewb

+0

不客氣! – adeneo