上一篇《Request 接收参数乱码原理解析一:服务器端解码原理》,分析了服务器端解码的过程,那么浏览器是根据什么编码的呢?

       1. 浏览器解码

       浏览器根据服务器页面响应Header中的“Content-Type: text/html; charset=gb2312”解码。修改web.config中“responseEncoding=utf-8”,发现服务器页面响应Header变成了“Content-Type: text/html; charset=utf8”。

  <system.web>
    <globalization requestEncoding="gb2312" responseEncoding="gb2312"/>
  </system.web>

Request 接收参数乱码原理解析二:浏览器端编码原理

       除了web.config中的globalization结点可以影响charset,修改页面Page_Load(配置文件仍为gb2312),发现页面charset输出也变成了utf-8,但同时也发现页面中的中文成了乱码。微软对Response.Charset的解释是获取或设置输出流的HTTP字符集,为什么会出现乱码?个人猜测可能整个页面是按照web.config中指定GB2312编码的,但输出的时候将字符集强制变成了utf-8。

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Charset = "utf-8";
        }

 

       2. 提交表单时的编码

       页面Get或者Post提交form表单数据时,会对表单中的中文进行编码,而编码方式是由服务器页面响应Header中的“Content-Type: text/html; charset=gb2312”确定的(和浏览器解码方式一致)。示例代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EncodeTest.aspx.cs" Inherits="Com.Shizi.Time8.UI.Test.WebTest.EncodeTest" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>页面编码测试</title>
    <script type="text/javascript" src="Scripts/jquery-2.1.1.min.js"></script>
</head>
<body>
    <form id="form1" action="EncodeTest.aspx" method="post">
        <div>
            <input type="text" name="name" id="name" value="北京" />
        </div>
        <div>
            <input type="submit" name="btnSumbit" value="sumbmit" /></div>
    </form>
    <div>
        <input type="button" name="btnAjaxPost" value="AJaxPost提交" onclick="AjaxPost()" />
        <input type="button" name="btnAjaxGet" value="AJaxGet提交" onclick="AjaxGet()" /></div>
    <div id="divMessage" style="color:red"></div>
    <script type="text/javascript">
        function AjaxGet() {
            $.ajax({
                type: "GET",
                url: "EncodeTest.aspx?namequery=" + $("#name").val(),
                data: { name: $("#name").val(), action: "ajax", methodtype: "get" },
                success: function (data) {
                    $("#divMessage").html(data);
                }
            });
        }
        function AjaxPost() {
            $.ajax({
                type: "POST",
                url: "EncodeTest.aspx?namequery=" + $("#name").val(),
                data: { name: $("#name").val(), action: "ajax", methodtype: "post" },
                success: function (data) {
                    $("#divMessage").text(data);
                }
            });
        }

    </script>
</body>
</html>
EncodeTest.aspx代码

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-12
  • 2021-06-20
  • 2022-12-23
  • 2021-06-04
  • 2021-04-16
猜你喜欢
  • 2021-08-27
  • 2022-03-04
  • 2021-07-09
  • 2022-02-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案