Ajax 는 JSon 과 xml 데 이 터 를 어떻게 전송 합 니까?
프론트 페이지
<%@ 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());
}
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
원생 Ajax와 jQuery Ajax의 차이점 예시 분석선언: 이번에 소개한 것은 aax와 백그라운드를 이용하여 데이터 교환을 하는 작은 예이기 때문에 demo는 서버를 통해 열어야 합니다.서버 환경은 구축하기 매우 좋다. 인터넷에서wamp나xampp를 다운로드하여 한 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.