The Ajax method ($.ajax()) is defined on the jQuery object to handle Ajax operations. After calling this method, the browser will send an HTTP request to the server. The ajax method has many attributes, but not all attributes are used for every call. This lecture introduces the function of each attribute in detail, and gives specific call cases, and returns text format data, JSON format data and xml format data from the server respectively. data.
$.ajax method usage specification
$.ajax() method common parameter list
attribute name |
illustrate |
type |
Set the request method ("POST" or "GET"), the default is "GET". Note: Other HTTP request methods such as PUT and DELETE can also be used, but only supported by some browsers. |
async |
Whether to set asynchronously, default value: true. By default, all requests are asynchronous. Set this option to false if you need to send synchronous requests. |
url |
The address from which the request was sent |
data |
The parameters requested to the server will be automatically converted to the request string format, format: {parameter name 1: value 1, parameter name 2: value 2...} |
success |
It is required to be a parameter of Function type, the callback function called after the request is successful, format: function(data[, textStatus]){}, data: the data returned by the server and processed according to the dataType parameter, textStatus is a string describing the status , can be omitted. |
error |
Requires a parameter of type Function, the function to be called when the request fails. function(){alert('Server exception!')} |
dataType |
The expected data type returned by the server. Available values are: text, json, xml, html, script, jsonp |
complete |
Requires a parameter of the Function type, the callback function to be called after the request is completed (whether the request succeeds or fails). |
The ajax method has many attributes, but not every call needs to be used, just use some parameters according to the situation
Specific case demonstration
The front-end code is as follows:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>JQuery中ajax支持应用</title>
<!--加载JQuery库-->
<script src="../js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function send(){
var userName = $("#userName").val();
console.log("userName=" + userName);
var url = "/ajaxProj/t4AjaxServlet"
$.ajax({
type:'post', //post或者get
async:true, //异步为true,同步为false
url: url,
//需要提交到后台的参数,键值对格式,多个参数逗号分隔
data:{
userName:userName,
id:1,
age:15,
action:'text'
},
success:function (data){
//响应成功执行该函数
console.log("执行成功:"+data);
$("#fonts").text(data);
},
error:function (data){
//响应失败执行该函数,比如404,500,405等
console.log("执行失败:" + data);
},complete:function(){
//不管执行成功,还是执行失败,最后都会执行
console.log("执行结束");
},
dataType:"text"
});
}
function sendJson(){
var userName = $("#userName").val();
console.log("userName=" + userName);
var url = "/ajaxProj/t4AjaxServlet"
$.ajax({
type:'post', //post或者get
async:true, //异步为true,同步为false
url: url,
//需要提交到后台的参数,键值对格式,多个参数逗号分隔
data:{
userName:userName,
id:1,
age:15,
action:'json'
},
success:function (data){
//响应成功执行该函数
console.log("执行成功:"+data);
var li = "<table>"
li += "<tr><td align='right'>id:</td><td>"+data.id+"</td></tr>"
li += "<tr><td align='right'>用户名称:</td><td>"+data.userName+"</td></tr>"
li += "<tr><td align='right'>用户年龄:</td><td>"+data.age+"</td></tr>"
li += "</table>";
$("#fonts").html(li);
},
error:function (data){
//响应失败执行该函数,比如404,500,405等
console.log("执行失败:" + data);
},complete:function(){
//不管执行成功,还是执行失败,最后都会执行
console.log("执行结束");
},
dataType:"json"
});
}
function sendXml(){
var userName = $("#userName").val();
console.log("userName=" + userName);
var url = "/ajaxProj/t4AjaxServlet"
$.ajax({
type:'post', //post或者get
async:true, //异步为true,同步为false
url: url,
//需要提交到后台的参数,键值对格式,多个参数逗号分隔
data:{
userName:userName,
id:1,
age:15,
action:'xml'
},
success:function (data){
//响应成功执行该函数
console.log("执行成功:"+data);
let membersData = data.getElementsByTagName("person");
console.log(membersData);
let id = membersData[0].childNodes[0].firstChild.nodeValue;
let userName = membersData[0].childNodes[1].firstChild.nodeValue;
let age = membersData[0].childNodes[2].firstChild.nodeValue;
let li = "<table>"
li += "<tr><td align='right'>id:</td><td>"+id+"</td></tr>"
li += "<tr><td align='right'>用户名称:</td><td>"+userName+"</td></tr>"
li += "<tr><td align='right'>用户年龄:</td><td>"+age+"</td></tr>"
li += "</table>";
$("#fonts").html(li);
},
error:function (data){
//响应失败执行该函数,比如404,500,405等
console.log("执行失败:" + data);
},complete:function(){
//不管执行成功,还是执行失败,最后都会执行
console.log("执行结束");
},
dataType:"xml"
});
}
</script>
</head>
<body>
<h2 align="center">JQuery中ajax支持应用</h2>
<hr>
用户名:<input type="text" name="userName" id="userName">
<input type="button" value="返回文本内容" onclick="send()">
<input type="button" value="返回json内容" onclick="sendJson()">
<input type="button" value="返回xml内容" onclick="sendXml()">
<hr>
服务器返回的结果:<font id="fonts" color="red" size="2"></font>
</body>
</html>
The backend code is as follows:
package com.servlet;
import com.alibaba.fastjson.JSONObject;
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;
import java.io.PrintWriter;
@WebServlet(name = "T4AjaxServlet",value = "/t4AjaxServlet")
public class T4AjaxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//获取返回的值
String action = request.getParameter("action");
String userName = request.getParameter("userName");
String id = request.getParameter("id");
String age = request.getParameter("age");
System.out.println("userName=" + userName + ",id=" + id + ",age=" + age);
//输出
if(action.equals("text")) {
out.println("返回结果:userName=" + userName);
}else if(action.equals("json")){
//字符串类型的值必须用双引号,如果是数值类型可以省略双引号
//String msg ="{\"userName\":\"" +userName+ "\",\"id\":\"" + id + "\",\"age\":" + age + "}";
//System.out.println(msg);
//out.println(msg);
//用fastjson包的类实现
JSONObject person = new JSONObject();
person.put("id",id);
person.put("userName",userName);
person.put("age",age);
out.println(person.toJSONString());
}else if(action.equals("xml")){
StringBuffer sb = new StringBuffer();
sb.append("<persons>");
sb.append("<person><id>"+id+"</id><userName>"+userName+"</userName><age>"+age+"</age></person>");
sb.append("</persons>");
out.println("<?xml version='1.0' encoding='utf-8' ?>");
out.println(sb.toString());
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
running result
There are also some convenient ways to write the ajax method.
$.get(): Issue a GET request.
$.getScript(): Read a JavaScript script file and execute it.
$.getJSON(): Issue a GET request to read a JSON file.
$.post(): Issue a POST request.
$.fn.load(): Read an html file and put it into the current element.
$.post method reference
//调用JQuery的post方法提交数据
let url = "/ajaxProj/collegeServlet"
$.post(
url,
{
参数1:值1,
参数2:值2,
参数3:值3
},
function (data){
//执行成功返回的结果
console.log(data);
},
"json"
);