日期:2014-05-16  浏览次数:20652 次

Ajax 介绍二

?

Ajax 介绍二
1.如何发送POST方式的请求
? open("post",url,true);
? setRequestHeader("Content-Type"
? ,"application/x-www-form-urlencoded");
? send("username=tom&age=1");
提示:有中文信息提交建议采用POST方式.
POST发送数据:
<html>
     <head >
           <script type= "text/javascript">
     function getXMLHttpRequest() {
           var xhr = null ;
           if (window.XMLHttpRequest) {
              xhr = new XMLHttpRequest();
              alert( "XMLHttpRequest");
          }

           else {
              xhr = new ActiveXObject("Microsoft.XMLHTTP" );
              alert( "Microsoft.XMLHTTP");
          }

           return xhr;
     }
     //当select选项发生改变时触发
     function viewComputer() {
           var xhr = getXMLHttpRequest();
           var id = document.getElementById("computer" ).value;
           var url = "computer.doo" ;
           //注册回调函数
          xhr.onreadystatechange = function() {
               var span = document.getElementById("span" );
               if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                         var price = xhr.responseText;

                        span.innerHTML = price;
                   } else {
                        span.innerHTML = "";
                   }
              } else {
                   span.innerHTML = "正在提取数据..." ;
              }
          };
          xhr.open( "POST", url);
           //post请求需要设置一个头参数
          xhr.setRequestHeader( "Content-Type",
                    "application/x-www-form-urlencoded" );
           //发送请求
          xhr.send( "id=" + id);
     }
</script>
     </head >

     <body >
           <h1>
              产品查看
           </h1>
           <hr />
           <select id= "computer" onchange ="viewComputer()">
               <option value= "1">
                   X200
               </option>
               <option value= "2">
                   X500
               </option>
               <option value= "3">
                   X600
               </option>
           </select>
           <hr />
           <span id= "span"></span >
     </body >
</html>
?2.POST提交中文乱码问题
? 在获取请求参数之前设置UTF-8编码,
? 原因是XMLHttpRequest对于post请求,
? 会采用UTF-8编码.
request.setCharacterEncoding("UTF-8");
  String name = request.getParameter("username");
??注意:request.setCharacterEncoding(?"utf-8");
? ? ??response.setContentType(?"text/plain;charset=utf-8"?);?
? ? ? ?utf-8的-不能丢,否则IE浏览器无法识别.
3.GET提交时,浏览器由于缓存问题,会阻止请求.
? 浏览器如果启用缓存,会将相同get请求的URL缓存,