学习内容:学习JavaWeb(Day44)
1、Ajax跨域操作 2、Ajax接收json数据 3、JQuery和Ajax 4、使用JavaScript模板简化操作
1、Ajax跨域操作
(1)Ajax不可以进行跨域请求
<body>
<input type="button" value="跳转百度" id="btn"/>
<script type="text/javascript">
var xmlHttp = null;
function createXmlHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xmlHttp = new XMLHttpRequest();
}
}
createXmlHttpRequest();
document.querySelector("#btn2").onclick = function () {
window.location.href = "https://www.baidu.com";
}
</script>
</body>
(2)使用代理模式进行跨域操作:通过在服务端进行跨域操作,将结果返回给Ajax,Ajax通过回调函数进行展示。 需要的包: fluent-hc-4.5.13.jar httpclient-4.5.13.jar httpclient-cache-4.5.13.jar httpclient-osgi-4.5.13.jar httpclient-win-4.5.13.jar httpcore-4.4.13.jar httpmime-4.5.13.jar jna-4.5.2.jar jna-platform-4.5.2.jar
(3)使用有道翻译API实现跨域翻译 用Ajax发送翻译请求,并调用回调函数接收服务端传来的xml文档:
document.querySelector("#btn").onclick = function () {
let value = document.querySelector("#cont").value;
httpReq.open("GET", "/trans?q=" + value);
httpReq.onreadystatechange = callback;
httpReq.send();
}
function callback(){
if(httpReq.readyState == 4){
if(httpReq.status == 200){
let result = httpReq.responseXML;
console.log(result.getElementsByTagName("paragraph")[0].childNodes[0].nodeValue);
}
}
}
注册申请有道翻译API后,使用http://hc.apache.org/中Apache HttpComponents项目HttpClient和HttpCore 模组提供的方法进行跨域操作。HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送Http请求变得容易,而且也方便开发人员测试接口(基于Http协议的),提高了开发的效率,也方便提高代码的健壮性。
创建工具类封装网络操作:
public class HttpReqUtil {
public static String getReq(String url) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
System.out.println(response1);
try {
HttpEntity entity1 = response1.getEntity();
String result = IOUtils.toString(entity1.getContent(),"UTF-8");
return result;
} finally {
response1.close();
}
}
}
创建Servlet:
@WebServlet("/trans")
public class TransServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String q = request.getParameter("q");
q = q.replace(" ","%20");
response.setContentType("text/xml;charset=utf-8");
String result = HttpReqUtil.getReq("https://fanyi.youdao.com/openapi.do?keyfrom=neverland&key=969918857&type=data&doctype=xml&version=1.1&q=" + q);
PrintWriter out = response.getWriter();
out.print(result);
out.close();
}
}
2、Ajax接收json数据
(1)JSON的全称是JavaScript Object Notation(即JavaScript对象标识),实际上是通过组合使用 JavaScript中的数组与键值对(hash)对象来描述数据的结构。 JSON中两种结构: 1. 数组用来表示有序结构 2. 键值对用来表示对应关系。
var json = { ‘name’ : ‘西安’ , ‘people’ : ‘387万’ , ‘area’ : ‘9871’ , ‘places’ : [ ‘兵马俑’ , ‘华清池’ , ‘骊山’ , ‘钟楼’ ] }
(2)JSON类库 ? Json-lib ? Gson ? FastJson ? Jackson
(3)使用Jackson需要的jar包 jackson-annotations-2.12.3.jar jackson-core-2.12.3.jar jackson-databind-2.12.4.jar
(4)对象转为json
BookDao bookDao = new BookDao();
Book book = bookDao.findById(88);
Map<String,Object> map = new HashMap<>();
map.put("name","Jerry");
map.put("code","100");
map.put("msg","删除成功!");
List<Book> bookList = bookDao.findAll();
ObjectMapper mapper = new ObjectMapper();
String jsonBook = mapper.writeValueAsString(bookList);
System.out.println(jsonBook);
对象转为json时可以在实体类中增加注解,可以加在定义属性上或get方法上。
public class Book {
@JsonProperty(value = "bookId")
private int id;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date datetime;
(5)json转为对象
String jsonString="[{\"id\":1,\"bookname\":\"java编程\",\"author\":\"James-Gosling\",\"publisher\":\"人民邮政出版社\"}]";
Book book1 = mapper.readValue(jsonString,Book.class);
Map map1 = mapper.readValue(jsonString,Map.class);
List<Book> listll = mapper.readValue(jsonString, new TypeReference<List<Book>>(){});
System.out.println(listll);
3、JQuery和Ajax
(1)使用Jquery发送Ajax请求
第一种:
$("#btn").click(function (){
$.ajax({
type: "POST",
url: "/json",
data: "name=John&location=Boston",
success: function(msg) {
alert("Data Saved: " + msg);
},
error:function(){
alert("服务器升级中!");
},
complete:function (){
alert("ajax 请求完成");
$("#loader").hide();
},
beforeSend:function (){
$("#loader").show();
}
});
});
第二种:这种方法需要指定type类型才能接收json数据类型
$("#btn").click(function (){
$.get("/json",{name:"Jack"},function (data){
alert(data);
});
});
第三种:
$("#btn").click(function (){
$.getJSON("/json",{name:"Rose",age:12},function (data){
$("#tab").html("");
$(data).each(function (){
let tr = "<tr><td>"+this.id+"</td><td>"+this.bookname+"</td></tr>";
$("#tab").append(tr);
});
});
});
4、使用JavaScript模板简化操作
(1)创建一个模板
<script type="text/template" id = "temp">
<tr><td>{{id}}</td><td>{{bookname}}</td><td>{{author}}</td><td>{{publisher}}</td></tr>
</script>
(2)使用模板将数据添加到jsp页面
$("#btn").click(function (){
$.getJSON("/json",{name:"Rose",age:12},function (data){
$("#tab").html("");
var template = Handlebars.compile($("#temp").text());
$(data).each(function (){
let tr = template(this);
$("#tab").append(tr);
});
});
});
|