JSONP jQuery Ajax 跨域请求

本文介绍了一个使用JSONP实现跨域请求的例子,通过JSP页面与Servlet交互,展示了前端如何发送跨域请求及后端如何响应。
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<base href="http://b.club:8081/JSPproject/">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    $(but).click(function(){
        $.ajax({
            url : "AjaxServlet" ,
            method : "post" ,
            data : {
                msg : $(msg).val() ,
                info : "hello"
            } ,
            dataType : "jsonp" ,
            jsonp : "jsonpcallback" ,
            success : function(data){
                alert(data.msg) ;
            } ,
            error : function(){
                alert("error") ;
            }
        }) ;
    }) ;
}) ;
</script>
</head>
<body>
    <input type="text" id="msg">
    <input type="button" id="but" value="按钮">
</body>
</html>


java代码

package me1.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AjaxServlet
 */
@WebServlet("/AjaxServlet")
public class AjaxServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjaxServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String code = "UTF-8" ;
        request.setCharacterEncoding(code);
        response.setCharacterEncoding(code);
        
        String msg = request.getParameter("msg") ;
        String info = request.getParameter("info") ;
        String jsonStr = "{\"msg\":\"" + msg + "\",\"info\":\"" + info +"\"}" ;
        String jsonpcallback = request.getParameter("jsonpcallback") ;
        
        System.out.println(jsonpcallback+"("+jsonStr+")");
        
        response.getWriter().println(jsonpcallback+"("+jsonStr+")") ;
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doGet(request, response);
    }

}



其实与正常的ajax是类似的,jsp代码ajax需要修改dataType,并增加jsonp。java代码需要在传递的json数据外面加上一个名(jsonpcallback)。

String jsonpcallback = request.getParameter("jsonpcallback") ;参数jsonpcallback就是一个标记,跟页面对应上就行。

比如,在页面输入 nihao,点击按钮,控制台输出结果为:jQuery31105591042713976494_1492651807928({"msg":"nihao","info":"hello"}),可以看到jsonpcallback的值并不是自己定义的。

在一台电脑上配置跨域访问

就是配置两个本地域名,上面程序ajax的url是b.club。。。,tomcat启动的时候使用a.club。。。就行了呗,其实都是localhost。

如何配置本地域名

修改 C:\Windows\System32\drivers\etc 路径下的hosts文件,可能需要管理员打开,可以先用管理员打开一个记事本软件,然后把hosts拖进去进行修改。

添加两条

127.0.0.1    a.club
127.0.0.1    b.club

原有的前面应该都有#,那是注释,这两个前面没有#,也可以为其他ip配置域名。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值