Jsonp的实现js跨域

由于浏览器的“同源策略”,js脚本只能调用同源(相同协议、域名、端口)的资源。但是,在页面上引入不同域上的js脚本文件却是可以的,jsonp正是利用这个特性来实现的。
示例如下:
Web项目Demo-1

package com.zzs.jsonp;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

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

import com.alibaba.fastjson.JSONObject;

public class JsonpServlet extends HttpServlet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
         try {  
                resp.setContentType("text/plain");  
                resp.setHeader("Pragma", "No-cache");  
                resp.setHeader("Cache-Control", "no-cache");  
                resp.setDateHeader("Expires", 0);  
                PrintWriter out = resp.getWriter();       
                JSONObject resultJSON = new JSONObject();
                resultJSON.put("result", "Hello");
                String jsonpCallback = req.getParameter("jsonpCallback");//客户端请求参数  
                out.println(jsonpCallback+"("+resultJSON.toJSONString()+")");//返回jsonp格式数据  
                out.flush();  
                out.close();  
              } catch (IOException e) {  
               e.printStackTrace();  
              }  
    }
}

Web项目 Demo-2

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<html>
  <head>
    <title>jsonptitle>
    <script type="text/javascript" src="js/jquery-1.10.2.min.js">script>
  head>

  <body>
    <button id="btn1">按钮1button>
  body>
  <script type="text/javascript">
    $(document).ready(function(){
        //jsonp
        $("#btn1").click(function(){
            $.ajax({
                url:"http://10.168.3.36:8080/Demo-1/jsonp",
                dataType:"jsonp",   
                type:"get",
                async:false,
                jsonp:"jsonpCallback",
                success:function(data){
                    alert(data.result);
                }
            });
        });
    });
  script>
html>

你可能感兴趣的:(JavaScript)