$.get()方法:
$.get()方法使用GET方式来进行异步请求。其语法格式如下:
$.get(url [, data] [, callback] [, type])
参数名称 | 类型 | 说明 |
---|---|---|
url | String | 请求的url地址 |
data(可选) | Object | 发送至服务器的key/value数据会作为QueryString附加到请求的URL中 |
callback(可选) | Function | 载入成功时回调函数的返回状态是success才调用的方法 |
type | String | 服务器返回内容的格式,包括xml、html、script、json、text和_default |
示例:
主页面:
<%--
Created by IntelliJ IDEA.
User: 19798
Date: 2019/10/3
Time: 10:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>get</title>
<script src="<%=request.getContextPath()%>/js/jquery-2.1.0.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
//get请求
$("#getId").on("click", function () {
var url = "response.jsp";
var params = {
"username":"tom",
"password":"123"
};
$.get(url, params, function (data) {
$("#resText").html(data);
});
});
});
</script>
</head>
<body>
<button id="getId" value="getAjax">getAjax</button>
<button id="postId" value="postAjax">postAjax</button>
<div id="resText"></div>
</body>
</html>
响应response.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
response.getWriter().write("用户名:" + username + "<br/>" + "密码:" + password);
%>
单机【getAjax】按钮,页面如下:
$.post()方法:
它与$.get()方法的语法和使用方式都完全相同,不过仍然有以下区别:
- GET请求会将参数跟在URL后进行传递,而POST请求则是作为HTTP消息的实体内容发送给Web服务器。当然,在Ajax请求中,这种区别对用于是透明的
- GET方式对传输的数据有大小限制(不大于2KB),而使用POST方式传递的数据量要比GET方式大的多
- GET方式请求的数据会被浏览器缓存起来,因此其他人就可以从浏览器的历史记录中读取到这些数据。而POST方式相对就安全许多
示例:
<%--
Created by IntelliJ IDEA.
User: 19798
Date: 2019/10/3
Time: 10:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>post</title>
<script src="<%=request.getContextPath()%>/js/jquery-2.1.0.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
//post请求
$("#postId").on("click", function () {
var url = "response.jsp";
var params = {
"username":"jerry",
"password":"456"
};
$.post(url, params, function (data) {
$("#resText").html(data);
});
});
});
</script>
</head>
<body>
<button id="getId" value="getAjax">getAjax</button>
<button id="postId" value="postAjax">postAjax</button>
<div id="resText"></div>
</body>
</html>
转载:https://blog.csdn.net/cold___play/article/details/102004993
查看评论