标签:show eval 响应状态 back ready 响应 数据 obj user
<%@ page language="java" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <title>study aJax</title> <script type="text/javascript"> function show(){ var ajax; if(window.XMLHttpRequest){ ajax=new XMLHttpRequest; }else if(window.ActiveXObject){ ajax=new ActiveXObject("Msxm12.XMLHTTP"); } ajax.onreadystatechange=function(){ //判断ajax状态码 if(ajax.readyState==4){ //判断响应状态码 if(ajax.status==200){ //获取响应数据 var result=ajax.responseText; //得到json对象,起名为user; eval("var user="+result); var table=document.getElementById("table"); //插入一行(0代表第一行,列同理) var tr=table.insertRow(1); //插入列 var td0=tr.insertCell(0); td0.innerHTML=user.uid; var td1=tr.insertCell(1); td1.innerHTML=user.uname; var td2=tr.insertCell(2); td2.innerHTML=user.loc; var td3=tr.insertCell(3); td3.innerHTML=user.desc; } } } //发送请求到ajaxServlet ajax.open("get","ajaxServlet?uname=javaee",true); ajax.send(null); } </script> <style type="text/css"> #test{ border:solid 2px; width:200px; height:100px; } </style> </head> <body> uname:<input type="text" id="uname" /> <input type="button" value="搜索" onclick="show()" /> <table id="table" border="1px"> <tr> <td>id</td> <td>uname</td> <td>loc</td> <td>desc</td> </tr> </table> <div id="test"></div> </body> </html>
public class TestAjax extends HttpServlet{ @Override public void service(HttpServletRequest request,HttpServletResponse response) throws IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String uname=request.getParameter("uname"); User u=new UserServiceImpl().UserService("javaee"); JsonObject jo=new JsonObject(); //JavaScript中声明对象 //response.getWriter().write("var user={uname:‘javase‘};"); //便用goson jar包,自动生成json response.getWriter().write(new Gson().toJson(u)); } public static void main(String[] args) { User u=new UserServiceImpl().UserService("javaee"); System.out.println(u.toString()); } }
标签:show eval 响应状态 back ready 响应 数据 obj user
原文地址:https://www.cnblogs.com/lastingjava/p/9898304.html