​AJAX各种实现方式​

​JQuery异步请求之$.post()​

​语法​

​例子​




​​AJAX各种实现方式​​



JQuery异步请求之$.post()



语法



$.post(url,[data],[callback],[type])


  • url:请求路径
  • data:请求参数
  • callback:回调函数
  • type:响应结果的类型



例子



例子:单击某个按钮,异步请求servlet,然后把响应内容返回给div



 jsp代码


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$.post()</title>
<script src="js/jquery-3.3.1.min.js"></script>
<style>
input{
width:300px;
height: 50px;
background-color:burlywood ;
}
div{
width:300px;
height: 200px;
background-color: pink;
}
</style>
<script>
function myClick() {
$.post("demo1", {"name":"林不渣", "age":26, "remarks":"没有女朋友"}, function (data) {
$("#div").html(data)
},"text");
}
</script>
</head>
<body>
<input type="button" value="单击我触发请求" onclick="myClick();" > <br><br><br>
<div id="div">

</div>
</body>
</html>


servlet的demo1代码


package com.lingaolu.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
* @author 林高禄
* @create 2020-08-07-14:58
*/
@WebServlet("/demo1")
public class Demo1 extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
Map<String, String[]> parameterMap = request.getParameterMap();
for(String[] sArr:parameterMap.values()){
for(String s:sArr){
writer.write("<h1>"+s+"</h1>");
}
}
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}


启动访问,单击按钮前

JQuery异步请求之$.post()_post



单击按钮后

JQuery异步请求之$.post()_异步_02