2011-11-18 105 views
3

我正在開發一個在客戶端和服務器端使用JavaScript + JQuery的Web應用程序。

我想作爲參數傳遞給AJAX請求的字符串之一在其內容中有'&'。

由於這個原因,請求的字符串被破壞。瀏覽器「認爲」該參數已經結束,因爲字符串上有'&'。

var hasChar = "This is a string that has a & in the content."; 
var doesntHave = "This one does not contain."; 
var dataString = "first=" + hasChar + "&second=" + doesntHave; 

$.ajax({ 
    type : "POST", 
    url : "myurl.php", 
    data : dataString, 
    cache : false, 
    success : function(html) { 
    } 
}); 

服務器接收的第一個參數是「這是有一個字符串」

我的問題:

如何我編碼在客戶端的字符串,我應該如何對其進行解碼在PHP服務器上。

回答

7

爲什麼不這樣做以下:

$.ajax({ 
     type : "POST", 
     url : "myurl.php", 
     data : { 
      'first': hasChar, 
      'second': doesntHave 
     }, 
     cache : false, 
     success : function(html) { 
     } 
    }); 

在這種情況下,jQuery將確保該字符串被正確編碼。

您也可以使用encodeURIComponent方法()的替代JS的內置功能正常編碼字符串:

var dataString = "first=" + encodeURIComponent(hasChar) + "&second=" + encodeURIComponent(doesntHave); 
5

您可以使用.param;

dataString = $.param({first: asChar, second: doesntHave}); 
8

讓jQuery的處理的hasChar爲您的編碼(和你的其他PARAMS):

var hasChar = "This is a string that has a & in the content."; 
var doesntHave = "This one does not contain."; 

$.ajax({ 
    type : "POST", 
    url : "myurl.php", 
    data : { first: hasChar, second: doesntHave }, 
    cache : false, 
    success : function(html) { 
    } 
}); 
1

,或者如果你想跳過$.param部分由@亞歷克斯-K文件檔案化

data : {'first': hasChar, 'second': doesntHave}, 
0

如果您希望服務器端的de /編碼使用urlencode()urldecode()

+0

這是不是一個真正的問題的答案。 – kapa

+0

@bazmegakapa:這是 - 編輯了這個問題。 「如何在_server_一側對字符串進行編碼......」是原始問題。 –

+0

這是一個錯字... – kapa

1

只需將它作爲一個對象:

var hasChar = "This is a string that has a & in the content."; 
var doesntHave = "This one does not contain."; 

$.ajax({ 
    type : "POST", 
    url : "myurl.php", 
    data : {first: hasChar, second: doesntHave}, 
    cache : false, 
    success : function(html) { 
    } 
}); 
0

試試這個

var dataString = {}; 
dataString["hasChar"] = "This is a string that has a & in the content."; 
dataString["doesntHave"] = "This one does not contain."; 

$.ajax({ 
    type : "POST", 
    url : "myurl.php", 
    data : dataString, 
    cache : false, 
    success : function(html) { 
    } 
}); 
1

您還可以使用encodeURI

var encodedData = encodeURI(dataString); 
$.ajax({ 
    type : "POST", 
    url : "myurl.php", 
    data : encodedData, 
    cache : false, 
    success : function(html) { 
    } 
}); 

Link

0

你的參數需要簡單的URL編碼。在PHP方面,你不需要解碼它們,一切都會正常工作。

有一個Javascript函數,名爲encodeURIComponent(),它將正確地對您的字符串進行網址編碼。因此,在基礎層面上,你可以這樣做:

var dataString = "first=" + encodeURIComponent(hasChar) + "&second=" + encodeURIComponent(doesntHave); 

如果你使用jQuery,它會自動處理這對你來說,如果in your $.ajax() call you pass it an object instead of a query string

數據選項可以包含的查詢字符串形式 key1 = value1 & key2 = value2,或形式爲{key1:'value1',key2: 'value2'}的地圖。如果使用後一種形式,則在發送數據之前使用jQuery.param()將數據轉換爲 查詢字符串。

所以你只需要做到這一點在你的代碼:

var dataString = { first: hasChar, second: doesntHave);