JQuery $.ajax()
$.ajax({type: 'POST', //请求方式 一般是get,posturl: url , // 这是必需的,规定把请求发送到哪个 URLdata: data , //这个是可选。映射或字符串值。规定连同请求发送到服务器的数据。java中用request.getParameter(key)来接收success: success , //可选。请求成功时执行的回调函数。 success:function(){}dataType: dataType //可选。规定预期的服务器响应的数据类型。默认执行智能判断(xml、json、script 或 html)});
案例
一个简单的表单验证的案例
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html><head><title>$Title$</title></head><script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js" type="text/javascript"></script><style>#contair{margin-top: 20vh;display: flex;flex-direction: row;justify-content:center ;}</style><body><div id="contair"><div>用户名:<input type="text" id="username"></div><div>密码:<input type="password" id="password"></div><button id="button" onclick="myfunction()">提交</button></div></body>
<script type="text/javascript" >function myfunction() {$.ajax({url:"http://localhost:8080/ajax_servlet_test_war_exploded/servlet1",dataType:"json",type:"post",data:{"username":$("#username").val(),"password":$("#password").val()},success:function (data) {var flag=data.flag;if(flag=="true"){alert(" 登陆成功!");}else{alert("账号或密码错误");}}});}
</script>
</html>
对应的servlet
package com.servlet.test;import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;public class ServletTest extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("application/json;charset=utf-8");request.setCharacterEncoding("utf-8");
// JSONArray jsonArray=new JSONArray();// jsonArray.add(0,jsonObject1);String username=request.getParameter("username");String password=request.getParameter("password");PrintWriter out=response.getWriter();System.out.println(username+"\n"+password);JSONObject jsonObject=null;if("xiuyuandashen".equals(username) && "123456".equals(password)){jsonObject =new JSONObject();jsonObject.put("flag","true");}else{jsonObject=new JSONObject();jsonObject.put("flag","false");}out.print(jsonObject);out.close(); //必须要关闭他,我也忘记为啥了 好像是不关闭不会传输?}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req,resp);}
}