$.ajax()
$.ajax()可以通过发送HTTP请求加载远程数据,是jQuery最底层的AJAX的实现,具有较高灵活性
举例:
servlet:
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<title>Document</title>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
$.ajax({
url:getPath()+"/AServlet",
type:"GET",
data:"name=张三",
dataType:"text",
success:function(data){
alert(data);
}
});
});
});
function getPath(){
var path = location.href;
var pname = location.pathname;
var index = path.indexOf(pname);
var projectName =pname.substring(0,pname.indexOf("/", 1));
return path.substring(0,index)+projectName+"/";
}
</script>
</head>
<body>
<input type="button" value="发送AJAX" id="btn" />
</body>
</html>
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/AServlet")
public class AServlet 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 {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
response.getWriter().print("hello:"+name);
}
}
运行结果:
$.get()
$.get()方法是JQuery封装的发送HTTP GET请求从服务器加载数据的AJAX方法。
语法:get(url, [data], [callback], [type])
eg.
$.post()
$.post()是jQuery封装的发送HTTP POST请求从服务器加载数据的AJAX方法。
语法:post(url, [data], [callback], [type]*)