处理get于post请求
-
为了简化ajax()函数的处理繁琐问题,所以在jQuery中又提供有两个新的衍生函数
- 处理get请求:$.get(地址:,{参数名称:内容,…},回调函数,“返回值类型”);
- 处理post请求:$.post(地址,{参数名称:内容,…},回调函数,“返回值类型”)
利用简化函数来进行信息处理
- 编写一个SimpleAjaxServlet.java程序类
package mao.shu.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/SimpleEchoServlet")
public class SimpleEchoServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求和回应编码
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
//设置返回内容类型
response.setContentType("text/html");
//接受请求参数,假设请求参数为msg
String msg = request.getParameter("msg");
String did = request.getParameter("did");
System.out.println("[msg=]"+msg);
System.out.println("[did=]"+did);
//回应内容
response.getWriter().print("{\"name\":\"Maoshu\",\"url\":\"www.maoshu.com\"}");
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
- 编写前台页面实现调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="js/jquery.min.js" charset="UTF-8"></script>
<title>Ajax异步处理</title>
<script type="text/javascript">
$(function(){
$("#subBut").on("click",function(){
//得到用户添加的内容
var pmsg = $("#msg").val();
//使用Ajax发送请求
$.post("SimpleEchoServlet",{msg:pmsg,did:20},function(data){
$("#showDiv").text("name="+data.name+",url="+data.url);
},"json");
});
})
</script>
</head>
<body>
<div id="inputDIv">
<input type="text" id="msg">
<input type="button" id="subBut" value="提交"/>
</div>
<!--请求回应显示层-->
<div id="showDiv">
</div>
</body>
</html>
- 执行结果
- 后台输出
- 页面
- 这样简写的方式很容易使用,但是他无法为请求出错时进行处理,这就看如何取舍了