Ajax 는 JSon 과 xml 데 이 터 를 어떻게 전송 합 니까?

16790 단어 AjaxJsonxml
ajax 전송 xml 데이터:데 이 터 를 xml 형식 으로 밀봉 하면 전송 이 가능 합 니 다.프론트 js 는 responseXML 로 xml 파 라 메 터 를 받 고 백 스테이지 읽 기 는 흐름 과 dom4j 로 해석 합 니 다.
프론트 페이지

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax XML      </title>
<script type="text/javascript">
  //get  ajax
  function send1(){
   alert("ok");
   var name=document.getElementsByName("name")[0].value;
   var age=document.getElementsByName("age")[0].value;
   var xhr=null;
   if(window.XMLHttpRequest){
    xhr=new XMLHttpRequest();
   }else{
    xhr=new ActiveXObject("Microsoft.XMLHttp");
   }

   var url="<c:url value='/XmlServlet?name='/>"+name+"&age="+age;
   //3      
   xhr.open("GET", url, true);
   //4            
   xhr.onreadystatechange=function(){
    if(xhr.readyState==4){//  
     if(xhr.status==200){//      
      var txt=xhr.responseText;
      alert(txt);

     }
    }
   };
   xhr.send(null);
  }
 </script>

<!--    xml            -->
<script type="text/javascript">
  //post  ajax
  function send2(){
   alert("222");
   //1  ajax  
   var xhr = null;
   if(window.XMLHttpRequest){//   
    xhr = new XMLHttpRequest();
   }else{//   
    xhr = new ActiveXObject("Microsoft.XMLHttp");
   }

   //2    
   var url = "<c:url value='/XmlServlet'/>";

   //3      
   xhr.open("POST", url, true);
   //4            
   xhr.onreadystatechange=function(){
    if(xhr.readyState==4){//  
     if(xhr.status==200){//      
      var xmlObj=xhr.responseXML;
      var users=xmlObj.getElementsByTagName("user");
      for(var i=0;i<users.length;i++){
       var id=users[i].getAttribute("id");
       var name=users[i].childNodes[0].firstChild.data;//xml  dom        , html      
       var age=users[i].childNodes[1].firstChild.data;//   childNodes["age"]
       alert(id+","+name+","+age);
      }
     }
    }
   };
   var name=document.getElementsByName("name")[0].value;
   var age=document.getElementsByName("age")[0].value;
   var xml="<user><name>"+name+"</name><age>"+age+"</age></user>";
   xhr.send(xml);
  }
 </script>

</head>
<body>
 Name:
 <input type="text" name="name">
 <br /> Age:
 <input type="text" name="age">
 <br />
 <input type="button" value="Get  " onclick="send1();" />
 <br />
 <input type="button" value="Post  " onclick="send2()" />
 <br />
</body>
</html>

배경 페이지

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax XML      </title>
<script type="text/javascript">
  //get  ajax
  function send1(){
   alert("ok");
   var name=document.getElementsByName("name")[0].value;
   var age=document.getElementsByName("age")[0].value;
   var xhr=null;
   if(window.XMLHttpRequest){
    xhr=new XMLHttpRequest();
   }else{
    xhr=new ActiveXObject("Microsoft.XMLHttp");
   }

   var url="<c:url value='/XmlServlet?name='/>"+name+"&age="+age;
   //3      
   xhr.open("GET", url, true);
   //4            
   xhr.onreadystatechange=function(){
    if(xhr.readyState==4){//  
     if(xhr.status==200){//      
      var txt=xhr.responseText;
      alert(txt);

     }
    }
   };
   xhr.send(null);
  }
 </script>

<!--    xml            -->
<script type="text/javascript">
  //post  ajax
  function send2(){
   alert("222");
   //1  ajax  
   var xhr = null;
   if(window.XMLHttpRequest){//   
    xhr = new XMLHttpRequest();
   }else{//   
    xhr = new ActiveXObject("Microsoft.XMLHttp");
   }

   //2    
   var url = "<c:url value='/XmlServlet'/>";

   //3      
   xhr.open("POST", url, true);
   //4            
   xhr.onreadystatechange=function(){
    if(xhr.readyState==4){//  
     if(xhr.status==200){//      
      var xmlObj=xhr.responseXML;
      var users=xmlObj.getElementsByTagName("user");
      for(var i=0;i<users.length;i++){
       var id=users[i].getAttribute("id");
       var name=users[i].childNodes[0].firstChild.data;//xml  dom        , html      
       var age=users[i].childNodes[1].firstChild.data;//   childNodes["age"]
       alert(id+","+name+","+age);
      }
     }
    }
   };
   var name=document.getElementsByName("name")[0].value;
   var age=document.getElementsByName("age")[0].value;
   var xml="<user><name>"+name+"</name><age>"+age+"</age></user>";
   xhr.send(xml);
  }
 </script>

</head>
<body>
 Name:
 <input type="text" name="name">
 <br /> Age:
 <input type="text" name="age">
 <br />
 <input type="button" value="Get  " onclick="send1();" />
 <br />
 <input type="button" value="Post  " onclick="send2()" />
 <br />
</body>
</html>

--------------------------------------------------------------------------------
Ajax 가 JSon 데 이 터 를 전송 하 는 요점 은 Apache 나 알 리 바 바 의 JSONarray 류 를 이용 하여 전송 합 니 다.
프론트 코드

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax Json      </title>
<script type="text/javascript">
 function ask1() {
  //1  ajax  
  var xhr = null;
  if (window.XMLHttpRequest) {//   
   xhr = new XMLHttpRequest();
  } else {//   
   xhr = new ActiveXObject("Microsoft.XMLHttp");
  }

  //2    
  var url = "<c:url value='/JsonServlet1'/>";

  //3      
  xhr.open("POST", url, true);

  //4            
  xhr.onreadystatechange = function() {
   if (xhr.readyState == 4) {//  
    if (xhr.status == 200) {//      
     //※※※※※       json 
     //js eval()     :          js        ,             
     var txt = xhr.responseText;
     var users = eval("(" + txt + ")"); //   json           json  
     for ( var i = 0; i < users.length; i++) {
      alert(users[i].id + "," + users[i].name + ","
        + users[i].age);
     }
    }
   }
  };
  //5   
  xhr.send(null);
 }

 function ask2() {
  //1  ajax  
  var xhr = null;
  if (window.XMLHttpRequest) {//   
   xhr = new XMLHttpRequest();
  } else {//   
   xhr = new ActiveXObject("Microsoft.XMLHttp");
  }

  //2    
  var url = "<c:url value='/JsonServlet2'/>";

  //3      
  xhr.open("POST", url, true);

  //4            
  xhr.onreadystatechange = function() {
   if (xhr.readyState == 4) {//  
    if (xhr.status == 200) {//      
     //※※※※※       json 
     //js eval()     :          js        ,             
     var txt = xhr.responseText;
     //alert(txt);
     //   json           json  
     var users = eval("(" + txt + ")"); 
     for ( var key in users)//map     
      alert("  :" + key + ", :" + users[key]);
     }
     //for ( var i = 0; i < users.length; i++) {//list     
      //alert(users[i].id +","+users[i].name+","+users[i].age);
     //}
   };
  };
  //5   
  xhr.send(null);
 }


 function ask3() {
  //1  ajax  
  var xhr = null;
  if (window.XMLHttpRequest) {//   
   xhr = new XMLHttpRequest();
  } else {//   
   xhr = new ActiveXObject("Microsoft.XMLHttp");
  }

  //2    
  var url = "<c:url value='/JsonServlet2'/>";

  //3      
  xhr.open("POST", url, true);

  //4            
  xhr.onreadystatechange = function() {
   if (xhr.readyState == 4) {//  
    if (xhr.status == 200) {//      
     //※※※※※       json 
     //js eval()     :          js        ,             
     var txt = xhr.responseText;
     //alert(txt);
     //   json           json  
     var users = eval("(" + txt + ")"); 
     for ( var key in users)//map     
      alert("  :" + key + ", :" + users[key]);
     }
     //for ( var i = 0; i < users.length; i++) {//list     
      //alert(users[i].id +","+users[i].name+","+users[i].age);
     //}
   };
  };
  //5   
  xhr.send(null);
 }
</script>

</head>
<body>
 <input type="button" onclick="ask1();" value="ajax      (    json  )" />
 <br />
 <input type="button" onclick="ask2();"
  value="ajax      ( apache    json  )" />
 <input type="button" onclick="ask3()" value="ajax      ( fastjson    json  )" />
</body>
</html>

JsonServlet1.java

package cn.hncu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hncu.domain.User;

public class JsonServlet1 extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
 }


 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //    service.dao.query(),             
  //         ,             
  response.setContentType("text/html;charset=utf-8");
  PrintWriter out = response.getWriter();
  List<User> users = new ArrayList<User>();
  users.add(new User("A001","Jack",20));
  users.add(new User("A002","Rose",22));
  users.add(new User("B001","  ",20));
  users.add(new User("B002","  ",30));
  String json="";
  // java   json      :[{name:"Jack",age:25}, {...}, {...} ]
  for(User u:users){
   if(json.equals("")){
    json="{name:\""+u.getName()+"\",id:\""+u.getId()+"\",age:"+u.getAge()+"}";
   }else{
    json = json +",{ name:\""+u.getName()+"\",id:\""+u.getId()+"\",age:"+u.getAge()+"}" ;
   }
  }
  json="["+json+"]";
  out.print(json);
 }

}

JsonServlet2.java

package cn.hncu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hncu.domain.User;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonServlet2 extends HttpServlet {

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType("text/html;charset=utf-8");
  PrintWriter out = response.getWriter();
  List<User> users = new ArrayList<User>();
  users.add(new User("A001","Jack",20));
  users.add(new User("A002","Rose",22));
  users.add(new User("B001","  ",20));
  users.add(new User("B002","  ",30));
  String strJson=com.alibaba.fastjson.JSONArray.toJSONString(users);
  System.out.println(strJson);
  // fastjson  (    jar )    list   json 
  Map<String, Object> map = new HashMap<String, Object>();
  map.put("addr", "  ");
  map.put("height", "170");
  map.put("marry", "no");
  map.put("user", new User("A003","  ",25));
  String strMap=com.alibaba.fastjson.JSONArray.toJSONString(map);

  out.print(strMap.toString());
 }

}

JsonServlet3.java

package cn.hncu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.hncu.domain.User;

public class JsonServlet3 extends HttpServlet {

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType("text/html;charset=utf-8");
  PrintWriter out = response.getWriter();
  List<User> users = new ArrayList<User>();
  users.add(new User("A001","Jack",20));
  users.add(new User("A002","Rose",22));
  users.add(new User("B001","  ",20));
  users.add(new User("B002","  ",30));
  // fastjson  (    jar )    list   json 
  JSONArray json=JSONArray.fromObject(users);
  String strJson=json.toString();
  System.out.println(strJson);

  Map<String, Object> map = new HashMap<String, Object>();
  map.put("addr", "  ");
  map.put("height", "170");
  map.put("marry", "no");
  map.put("user", new User("A003","  ",25));
  JSONObject obj = JSONObject.fromObject(map);
  System.out.println(obj.toString());

  out.print(obj.toString());
 }

}


이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기