$.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>gettitle>
<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">getAjaxbutton>
<button id="postId" value="postAjax">postAjaxbutton>
<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 + "
" + "密码:" + password);
%>
它与$.get()方法的语法和使用方式都完全相同,不过仍然有以下区别:
示例:
<%--
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>posttitle>
<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">getAjaxbutton>
<button id="postId" value="postAjax">postAjaxbutton>
<div id="resText">div>
body>
html>