jquery使用ajax傳內容到asp.net亂碼解決

來源:互聯網
上載者:User

 

Jquery強大的功能越來越收到廣大朋友的喜愛,不過Ajax方面就有點太不照顧中國人民的感情了

資料傳遞編碼僅支援UTF-8,這個雖然是全球統一編碼,但是也要考慮一下中國人名以磁碟為基礎的網站的編碼問題吧

而且在jquery的發送端,無論你設定了程式級編碼還是頁面級編碼,jquery都會使用utf-8的編碼方式傳遞過去

有些網站都運營好長事件了,完全修改UTF-8確實有點困難,好了牢騷就發到這裡,下面是自己寫的一個解決例子

希望能對大家有一些協助。

原理:

在ajax發送端使用escape方法。然後在接收端(顯示)使用 unescape方法轉換

jquery的ajax傳遞參數都是轉換成utf-8編碼的,所以有發送前加上url編碼函數escape(),之後asp.net接收處理為Server.UrlDecode(Request[參數])

例子如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="DYJ.stockSms.test" %>
<!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>
    <script type="text/javascript" src="jq.js"></script>
    <script>
        function hq() {
            $.post("test.aspx", { "stock": escape("www結合中文測試123") }, function(data) {
            $("#show").html(unescape(data));  //這裡unescape一下就可以了 
                }
            );   
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type=button value="測試" onclick="hq();" runat="server" />
    </div>
    <span id="show"></span>
    </form>
</body>
</html>

後台代碼:  

  protected void Page_Load(object sender, EventArgs e)
        {

            if (Request["stock"] != null)
            {
                Response.Expires = -1;
                Response.Write(Server.UrlDecode(Request["stock"]));
                Response.End();
            }
        }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.