在JavaScript中通過URL傳遞漢字的方法

來源:互聯網
上載者:User

利用JavaScript通過URL方式向後台代碼傳值是一種經常用到的手段,但在傳遞漢字時經常會出現字元不全或變成亂碼的問題,其原因是由於用戶端IE瀏覽器的編碼方式為GB2312(簡體中文版WINDOWS的預設設定),而背景C#代碼使用utf8編碼(建立WEB工程的預設配置)。
網上有很多方案解決該問題,如將web.config的編碼方式改為GB2312、在用戶端通過escape先編碼再傳,個心體會都不是很理想或有些特殊字元不支援。經過比較我決定使用encodeURIComponent在用戶端進行編碼,再傳值,除了“/”不支援(但實際開發中很少需要傳遞該值,如果真有此請況,再加一層判斷即可。
encodeURIComponent的協助文檔如下:
encodeURIComponent 方法
將文本字串編碼為一個統一資源識別項 (URI) 的一個有效組件。
encodeURIComponent( encodedURIString )
必選的 encodedURIString 參數代表一個已編碼的 URI 組件。
說明
encodeURIComponent 方法返回一個已編碼的 URI。如果您將編碼結果傳遞給 decodeURIComponent ,那麼將返回初始的字串。因為encodeURIComponent 方法對所有的字元編碼,請注意,如果該字串代表一個路徑,例如 /folder1/folder2/default.html ,其中的斜杠也將被編碼。這樣一來,當該編碼結果被作為請求發送到 網頁伺服器時將是無效的。如果字串中包含不止一個 URI 組件,請使用 encodeURI 方法進行編碼。
要求
版本 5.5
請參閱
decodeURI 方法 | decodeURIComponent 方法
應用於: Global 對象

我做了一個小例子來展現該效果
Default.aspx代碼: 複製代碼 代碼如下:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>無標題頁</title>
</head>
<script type="text/javascript" language="javascript">
function callURL(Value1, Value2)
{
document.URL = "Default.aspx?Value1=" + encodeURIComponent(Value1) + "&Value2=" + encodeURIComponent(Value2);
}
</script>
<body>
<form id="form1" runat="server">
<div>
Value1=<input id="Text1" type="text" value="1234567890"/><br />
Value2=<input id="Text2" type="text" value="中華人民共和國"/>
<br />
<input id="Button1" type="button" value="提交" onclick="callURL(Text1.value, Text2.value)"/></div>
</form>
</body>
</html>

Default.aspx.cs代碼: 複製代碼 代碼如下:using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string tmpValue1 = "";
string tmpValue2 = "";
if (Request.QueryString["Value1"] != null)
{
tmpValue1 = Request.QueryString["Value1"].ToString();
}
if (Request.QueryString["Value2"] != null)
{
tmpValue2 = Request.QueryString["Value2"].ToString();
}
Response.Write("Value1=" + tmpValue1 + "<br />" + "Value2=" + tmpValue2);
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.