现在的位置: 首页 > 综合 > 正文

XmlHttpRequest的Post请求方式示例

2017年12月21日 ⁄ 综合 ⁄ 共 1009字 ⁄ 字号 评论关闭

示例代码如下(注意页面编码一定要是UTF-8,因为XmlHttpRequest对象的默认编码是UTF-8):
      function Request(url) {
           var xmlHttp = CreateXMLHttpRequest();
         var content = "m_title=title&m_content=content";
           xmlHttp.open('POST', url, true);
         xmlHttp.setRequestHeader("Content-Length", content.length);
         xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
           xmlHttp.onreadystatechange=function(){
               if(xmlHttp.readyState==4){
                   if(xmlHttp.status==200){
                         alert(xmlHttp.responseText);
                       }
                 }
           }
          xmlHttp.send(null);
      }

由于XMLHttpRequest POST的内容是用UTF-8编码,所以在服务端要先把request的编码改为UTF-8.
而且客户端post的表单是x-www-form-urlencoded的,所以也要对post的内容进行编码encodeURIComponent()函数
escape() 只是为 ASCII字符 做转换工作,转换成的 %unnnn 这样的码,如果要用更多的字符如 UTF-8字符库
就一定要用 encodeURIComponent() 或 encodeURI() 转换才可以成 %nn%nn
还有
escape() 不编码这些字符:   @*/+
encodeURI() 不编码这些字符:   !@#$&*()=:/;?+'
encodeURIComponent() 不编码这些字符:   !*()'

还是推荐使用encodeURIComponent()函数来编码比较好。

 

抱歉!评论已关闭.