当前位置: 代码迷 >> Ajax >> Ajax 引见二
  详细解决方案

Ajax 引见二

热度:261   发布时间:2012-11-25 11:44:31.0
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缓存,
如果再次发出缓存的URL请求,浏览器会将缓存结果返回.

?

为了避免缓存问题,应如下解决:
第一种:采用URL后跟上时间戳来防止浏览器缓存,如:
user.jsp?userId="+userId+"&timestampt="+new Date().getTime()
第二种:加入清除缓存的代码
response.setContentType("text/html");
response.setHeader("Cache-Control","no-store");//HTTP1.1
response.setHeader("Pragma","no-cache");//HTTP1.0
response.setDateHeader("Expires",0);
?
提示:POST请求不会缓存

4.下拉单级联示例
? 1)创建表,编写entity类,DBUtil,DAO
entity:
public class City
{
     private int id ;
     private String name;
     private int parentId ;
     public int getParentId()
     {
           return parentId ;
     }
     public void setParentId(int parentId)
     {
           this.parentId = parentId;
     }
     public int getId()
     {
           return id ;
     }
     public void setId(int id)
     {
           this.id = id;
     }
     public String getName()
     {
           return name ;
     }
     public void setName(String name)
     {
           this.name = name;
     }
 }
?
DBUtil:
public class DBUtil {
     public static Connection getConnection() throws Exception{
           Connection conn = null;
           try {
              Class. forName("com.mysql.jdbc.Driver");
              conn = DriverManager.getConnection(
                         "jdbc:mysql://localhost:3306/jd1206db?" +
                         "useUnicode=true&characterEncoding=utf8" ,
                         "root","1234" );
          } catch (Exception e) {
              e.printStackTrace();
               throw e;
          }
          
           return conn;
     }
     public static void close(Connection conn){
           if(conn != null ){
               try {
                   conn.close();
              } catch (SQLException e) {
                   e.printStackTrace();
              }
          }
     }
     public static void main(String[] args) {
     }
}
?DAO:
public class CityDAO {
     public List<City> findByParentId( int parentId) throws Exception{
          String sql = "select * from t_city where parent_id=?";
          Connection conn = DBUtil.getConnection();
          PreparedStatement pst = conn.prepareStatement(sql);
          pst.setInt(1, parentId);
          ResultSet rs = pst.executeQuery();
          List<City> list = new ArrayList<City>();
           while(rs.next()){
              City city = new City();
              city.setId(rs.getInt( "id"));
              city.setName(rs.getString( "name"));
              list.add(city);
          }
           DBUtil.close(conn);
           return list;
     }
}
?
2)编写Servlet组件
public class CityServlet extends HttpServlet{
     
     public void service(HttpServletRequest request
              , HttpServletResponse response){
          String pid = request.getParameter( "parentId");
           CityDAO cityDao = new CityDAO();
           try{
               List<City> list =
                   cityDao.findByParentId(Integer. parseInt(pid));
              StringBuffer s = new StringBuffer();
               for(City c : list){
                   s.append(c.getId()+ ":"+c.getName());
                   s.append( "|");
              }
              s.delete(s.length()-1, s.length()); //将最后一个"|"删除
              System. out.println(s.toString());
               //将查询结果字符串输出,返回给 ajax请求
               response.setContentType( "text/plain;charset=utf-8");
               PrintWriter out = response.getWriter();
              out.print(s.toString());
              out.flush();
              out.close();
          } catch(Exception ex){
              ex.printStackTrace();
          }
     }
}
?
3)编写onload事件处理,发送Ajax请求加载
? 第一个下拉单.
function loadC1(){
           var xhr = getXMLHttpRequest();
          url = "city.do?parentId=0";
          xhr.open( "get",url,true );
          xhr.onreadystatechange = function(){
               //获取服务器返回的字符串,解析后生成Option
               if(xhr.readyState == 4){
                    if(xhr.status == 200){
                       var txt = xhr.responseText;//获取返回信息
                       //按|字符切割,获取id:name字符串数组
                       var arr = txt.split("|" );
                       //循环arr数组,将每一个id:name字符串生成一个Option
                       for(var i=0;i<arr.length;i++){
                         var s = arr[i];//获取id:name字符串
                         var arr1 = s.split(":" );//获取arr1数组,存储id和name
                         var opt = new Option(arr1[1],arr1[0]);
                         var optC1 = document.getElementById("c1" );
                        optC1.options[i] = opt; //将option对象给select指定
                       }
                   }
              }
           }
          xhr.send( null);
     }
?
? 4)编写第一个下拉单的onchange事件,发送Ajax请求
? 加载第二个下拉单

//根据C1选项加载C2的Option
     function loadC2(){
           var xhr = getXMLHttpRequest();
           var c1Id = document.getElementById("c1" ).value;
          url = "city.do?parentId="+c1Id;
          xhr.open( "get",url,true );
          xhr.onreadystatechange = function(){
               //获取服务器返回的字符串,解析后生成Option
               if(xhr.readyState == 4){
                    if(xhr.status == 200){
                       var txt = xhr.responseText;//获取返回信息
                       //按|字符切割,获取id:name字符串数组
                       var arr = txt.split("|" );
                       var optC2 = document.getElementById("c2" );
                       optC2.options.length = 0; //清空options
                       //循环arr数组,将每一个id:name字符串生成一个Option
                       for(var i=0;i<arr.length;i++){
                         var s = arr[i];//获取id:name字符串
                         var arr1 = s.split(":" );//获取arr1数组,存储id和name
                         var opt = new Option(arr1[1],arr1[0]);
                        optC2.options[i] = opt; //将option对象给select指定
                       }
                   }
              }
           }
          xhr.send( null);
     }
?5.JSON技术
? JavaScript Object Notation
? JavaScript对象格式
? 1)json对象格式
 {"key1":value1,"key2":value2}

var p2 = {
                    "name":"jack" ,
                    "address":{"city" :"北京" ,"street" :"某大街" }             
          };
          alert(p2.address.city+ ":"+p2.address.street);
?
2)数组格式
??? [元素1,元素2,元素3]?
??? json对象数组 [{...},{...},{...}]
var cities = [{"id" :1,"name" :"北京" },
                       { "id":2,"name" :"上海" },
                       { "id":3,"name" :"南京" }];
          
           function loadc1()
          {
               var select = document.getElementById("c1" );
               for(i=0;i<cities.length;i++)
              {
                    var opt = new Option(cities[i].name,cities[i].id);
                   select.options[i] = opt;
              }
          }
?

3)如何将服务器端的Java对象
? ???? 或集合转换成json字符串
??? a.引入json.jar开发包
??? b.将Java对象转换json对象格式的字符串
??? JSONObject json =
????? ???? JSONObject.formObject(java对象);
??? String jsonStr = json.toString();
??? c.将Java集合转换成json对象数组格式的字符串
??? JSONArray json =
??? ???? JSONArray.fromObject(集合);
????????? String jsonStr = json.toString();
public class AtionServlet extends HttpServlet
{
     public void service(HttpServletRequest request, HttpServletResponse response)
               throws ServletException, IOException
     {
          request.setCharacterEncoding( "utf-8");
          response.setContentType( "text/html;charset=utf-8");
          PrintWriter out = response.getWriter();
          
          City city = new City();
          city.setId(5);
          city. setName("北京");
          city.setParentId(0);
           //利用json.jar
          JSONObject jsonArray = JSONObject.fromObject(city);
          
          String citystr = jsonArray.toString();
          System. out.println(citystr);
          out.print(citystr);
          out.flush();
          out.close();
     }
}
??4)如何将客户端js字符串转换成json对象
eval("("+txt+")");
?






?

  相关解决方案