$.post(url,[data],[callback],[type])
url:发送请求地址。
data:待发送 Key/value 参数。
callback:发送成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。
$.post(url,[data],[callback],[type])
这个方法和$.get()用法差不多,唯独多了一个type参数,那么这里就只介绍type参数吧,其他的参考上面$.get()的。
type:type为请求的数据类型,可以是html,xml,json等类型,如果我们设置这个参数为:json,那么返回的格式则是json格式的,如果没有设置,就和$.get()返回的格式一样,都是字符串的。
最后写一个$.post()的实例供大家参考:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/baidutest/search.js"></script>
百度一下
search.js
$(function() {
$("#word").keyup(function() {
var word = $(this).val();
$.post("/Day19/baiduservlet",{"word":word}, function(data) {
if(word != "") {
$("#d1").show().html(data);
} else {
$("#d1").hide();
}
})
})
})
info.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
${w.name }
servlet (省略数据库操作)
public void init() throws ServletException {
System.out.println("开始");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
request.setCharacterEncoding("UTF-8");
String word = request.getParameter("word");
baiduservice service=new baiduservice();
List<baidu> list = service.service(word);
request.setAttribute("list", list);
request.getRequestDispatcher("/baidutest/info.jsp").forward(request, response);
} catch (SQLException e) {
System.out.println(e);
//像这个在catch中再throw new RuntimeException的,是为了中断程序,因为runtime的异常会中断程序,不再运行下去
throw new RuntimeException();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
System.out.println("开始");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
request.setCharacterEncoding("UTF-8");
String word = request.getParameter("word");
baiduservice service=new baiduservice();
List<baidu> list = service.service(word);
request.setAttribute("list", list);
request.getRequestDispatcher("/baidutest/info.jsp").forward(request, response);
} catch (SQLException e) {
System.out.println(e);
//像这个在catch中再throw new RuntimeException的,是为了中断程序,因为runtime的异常会中断程序,不再运行下去
throw new RuntimeException();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}