【JavaWeb】jquery的get、post、ajax方法

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

url:代表请求的服务器地址
data:代表请求服务器端的数据(可以是key=value形式也可以是json格式)
callback:表示服务器端成功响应所触发的函数(只有正常成功返回才执行)
type:表示服务器端返回的数据类型(jquery会根据指定的类型自动类型转换)
常用的返回类型:text、json、html等

代码实现:
前端jsp:

//js
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    function fn1() {
        //get异步访问
        $.get(
            "${pageContext.request.contextPath}/ajaxjqueryServlet",//url地址
            {"name":"zhangsan","age":20},//请求参数
            function (data) {//执行成功后的回调函数
                alert(data);
            },
            "text"
        );
    }
    function fn2() {
        //post异步访问
        $.post(
            "${pageContext.request.contextPath}/ajaxjqueryServlet",//url地址
            {"name":"李四","age":21},//请求参数
            function (data) {//执行成功后的回调函数
                alert(data);
            },
            "text"
        );
    }
</script>

//jsp:
<div class="div1">
    <input type="button" value="get访问服务器" onclick="fn1()">
    <span id="span1"></span>
</div>
<div class="div1">
    <input type="button" value="post访问服务器" onclick="fn2()">
    <span id="span2"></span>

服务器端:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        //response.getWriter().write("success...."+name+" "+age);//返回值为text时
        //java代码只能返回json格式的字符串
        response.getWriter().write("{\"name\":\""+name+"\",\"age\":"+age+"}");//返回值为json时
    }

运行结果:
getpost

3)$.ajax({option.value1,option2:value2…});
常用的option有如下:
async:是否异步,默认是true代表异步
data:发送到服务器的参数,建议使用json格式
dataType:服务器端返回的数据类型,常用text和json
success:成功响应执行的函数,对应的类型是fuction类型
type:请求方式:POST/GET
url:请求服务器端地址

代码实现:
前端jsp:

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    function fn3() {
        $.ajax({
            url:"${pageContext.request.contextPath}/ajaxjqueryServlet",
            async:true,
            type:"POST",
            data:{"name":"wangwu","age":20},
            success:function (data) {
                alert(data.name);
            },
            error:function () {
                alert("请求失败");
            },
            dataType:"json"
        });
    }
</script>

运行结果:
ajax

发布了17 篇原创文章 · 获赞 1 · 访问量 637

猜你喜欢

转载自blog.csdn.net/weixin_43316702/article/details/104858821
今日推荐