jQuery中ajax的get和post请求

一、Get请求

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="css/bootstrap.min.css"/>
    <%--引入jQuery--%>
    <script src="js/jquery.min.js"></script>
    <script>

        jQuery(function () {
            jQuery("#btn").click(function () {
//jQuery.get(url, [data], [callback], [type])
// 这是一个简单的 GET 请求功能以取代复杂 $.ajax 。请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。
// 参数
//urlString待载入页面的URL地址
//data (可选)Map待发送 Key/value 参数。
// callback (可选)Function载入成功时回调函数。
// type (可选)String返回内容格式,xml, html, script, json, text, _default。
                jQuery.get("./add?num="+$("#num").val()+"&name="+$("#name").val(),function (data) {
                    //所需要的值直接就在返回值中  所以直接从返回值中获取
                    console.log(data);
                   if(data.msg==1){
                        alert("添加成功")
                    }else{
                        alert("添加失败")
                    }

                },"json")

            })
        })

    </script>
</head>
<body>
<form>
    序号<input id="num">
    姓名<input id="name">
    <button type="button" id="btn">添加</button>
</form>
</body>
</html>

二、Post请求

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%--引入jQuery--%>
    <script src="js/jquery.min.js"></script>
    <script>
        jQuery(function () {

            jQuery("#btn").click(function () {
                var da = {};
                da.num = $("#num").val();
                da.name = $("#name").val();
//       jQuery.post(url, [data], [callback], [type])
// 这是一个简单的 POST 请求功能以取代复杂 $.ajax 。请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。
// 参数
// urlString发送请求地址。
// data (可选)Map待发送 Key/value 参数。
// callback (可选)Function发送成功时回调函数。
// type (可选)String返回内容格式,xml, html, script, json, text, _default。
                jQuery.post("./add",da,function (data) {
                    //所需要的值直接就在返回值中  所以直接从返回值中获取
                    console.log(data);
                    if(data.msg==1){
                        alert("添加成功")
                    }else{
                        alert("添加失败")
                    }

                },"json")

            })
        })

    </script>
</head>
<body>
<form>
    序号<input id="num">
    姓名<input id="name">
    <button type="button" id="btn">添加</button>
</form>
</body>
</html>

统一的接收方式(使用到了commons.io包,fastjson包)

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;


public class addServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        //消除乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //使用键值对来对数据进行接受
        String num = request.getParameter("num");
        String name = request.getParameter("name");
        //加入一个判断条件,如果键值对的方式没有接收到数据则使用json进行接收
        System.out.print(num+"---"+name);
        if(num==null){
            //json形式的数据接收需要用到流
            InputStream in = request.getInputStream();
            //将流转换为字符串  使用的是org.apache.commons.io.IOUtils包下的内容
            String str = IOUtils.toString(in,"utf-8");
            //将字符串转换成json格式对象   使用的是com.alibaba.fastjson.JSONObject包下的方法
            JSONObject jsonObject = JSON.parseObject(str);
            //将json对象中的内容提取出来
            num = jsonObject.getString("num");
            name = jsonObject.getString("name");
        }
        //从域中取得一个集合
        Map list =(Map) request.getServletContext().getAttribute("list");
       //如果这个集合不存在,就新建一个集合
        if (list==null){
            list = new HashMap();
            //把集合放到域中
            request.getServletContext().setAttribute("list",list);
        }
        //新建一个JSON对象进行值的存入
        JSONObject json = new JSONObject();
       //对取到的值进行判断
        if(list.containsKey(num)){
            //如果key已经存在 则不让放入
            //用jsonobject.put()方法将值放入 json对象
            json.put("msg",0);    //第一个为key  第二个为value
        }else{
            //如果key不存在 则将取到的值放入
            list.put(num,name);
            //用jsonobject.put()方法将值放入 json对象
            json.put("msg",1);
        }
        //然后将 map 集合 也放入到json对象中
        json.put("list",list);
        System.out.print(json.getString("msg"));
        //将json对象打包 做为返回值发送到jsp中
        //JSON.toJSONString()这个方法是为了将json对象转换为字符串   第一个字段为需要传输的对象 第二个是为了转义"/"
        response.getWriter().print(JSON.toJSONString(json, SerializerFeature.WriteSlashAsSpecial));
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doPost(request,response);
    }
}

猜你喜欢

转载自blog.csdn.net/scbiaosdo/article/details/81368311