浅谈JQuery+ajax+jsonp 跨域访问

(编辑:jimmy 日期: 2026/1/15 浏览:2)

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="/UploadFiles/2021-04-02/jquery-1.7.2.js">

二. 服务器端

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(); 
   } 
  } 
} 

以上就是小编为大家带来的浅谈JQuery+ajax+jsonp 跨域访问全部内容了,希望大家多多支持~

一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。