基于jQuery与JSONP实现跨域数据交互

作者:工具松鼠时间:2026-10-30 09:41:52浏览:568

本文介绍利用JSONP技术解决浏览器跨域限制的方法,通过jQuery的ajax或getJSON实现前端与后端的数据交互。涵盖客户端请求配置及服务器端返回JSONP格式数据的Java代码实现,帮助开发者理解并应用该方案。

JSONP(JSON with Padding)是JSON格式的一种使用模式,允许网页从不同的网域获取数据。

客户端实现

一、客户端实现


<!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> 
<script type="text/javascript" src="resource/js/jquery-1.7.2.js"></script> 
</head> 
<script type="text/javascript"> 
$(function(){   
  /* 
  //简写形式,效果相同 
  $.getJSON("http://app.example.com/base/json.do?sid=1494&busiId=101&jsonpCallback=?", 
      function(data){ 
        $("#showcontent").text("Result:"+data.result) 
  }); 
  */ 
  $.ajax({ 
    type : "get", 
    async:false, 
    url : "http://app.example.com/base/json.do?sid=1494&busiId=101", 
    dataType : "jsonp",//数据类型为jsonp 
    jsonp: "jsonpCallback",//服务端用于接收callback调用的function名的参数 
    success : function(data){ 
      $("#showcontent").text("Result:"+data.result) 
    }, 
    error:function(){ 
      alert('fail'); 
    } 
  });  
}); 
</script> 
<body> 
<div id="showcontent">Result:</div> 
</body> 
</html> 

在客户端代码中,通过jQuery发起请求。示例代码使用了jquery-1.7.2.js库,并在页面加载完成后执行脚本。核心逻辑是调用$.getJSON或$.ajax方法,指定目标URL(如http://app.example.com/base...),并处理返回的数据。成功回调函数中,将data.result的值显示在id为showcontent的div元素中;失败时则弹出'fail'提示。


import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.HashMap; 
import java.util.Map; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import net.sf.json.JSONObject; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
 
@Controller 
public class ExchangeJsonController { 
  @RequestMapping("/base/json.do") 
  public void exchangeJson(HttpServletRequest request,HttpServletResponse response) { 
    try { 
    response.setContentType("text/plain"); 
    response.setHeader("Pragma", "No-cache"); 
    response.setHeader("Cache-Control", "no-cache"); 
    response.setDateHeader("Expires", 0); 
    Map<String,String> map = new HashMap<String,String>();  
    map.put("result", "content"); 
    PrintWriter out = response.getWriter();    
    JSONObject resultJSON = JSONObject.fromObject(map); //根据需要拼装json 
    String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数 
    out.println(jsonpCallback+"("+resultJSON.toString(1,1)+")");//返回jsonp格式数据 
    out.flush(); 
    out.close(); 
   } catch (IOException e) { 
    e.printStackTrace(); 
   } 
  } 
} 

服务器端实现

二、服务器端实现

作者最新文章