JQuery ajax设置Request Headers

1、前端页面


<html>
<head>
    <meta charset="UTF-8">
    <script src="/js/jquery.js" >script>
    <script type="text/javascript">
    $(function(){
        $.ajax({
            url:'/后台接口路径',
            type:'POST',
             beforeSend: function(request) {
                 request.setRequestHeader("key", "test");
                 request.setRequestHeader("key2", "test2");
             },
             dataType:'html',
             success:function(res){
                 console.log(res);
             }
        })
    })
    script>
head>
<body>
body>
html>

2、后台接口(此处用Servlet)

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String key = req.getHeader("key");
        String key2 = req.getHeader("key2");
        System.out.println(key+"---------");
        System.out.println(key2+"---------");
        PrintWriter out = resp.getWriter();  
        out.print("success");
    }

3、输出结果
后台输出结果:
test———
test2———
前端输出结果:
success

你可能感兴趣的:(java,jquery,ui,jquery)