使用jsonp進行跨域訪問

來源:互聯網
上載者:User

標籤:des   blog   http   java   使用   os   

一、使用情境

  當我們請求非本伺服器的資源的時候,瀏覽器會禁止訪問,並提示不允許跨域訪問。此時我們可以使用jsonp這種請求方式,從其他伺服器擷取資源。在用戶端調用提供jsonp支援的介面,擷取jsonp格式的資料。

二、用戶端的實現

  用戶端使用jsp,用js發送ajax請求,代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>jsonp</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><script type="text/javascript" src="./js/jquery-1.9.1.min.js"></script></head><body><script type="text/javascript">jQuery(document).ready(function() {$.ajax( {type : "get",async : false,url : "http://127.0.0.1:8089/test2/TestServlet?id=1",dataType : "jsonp",jsonp : "callback",//傳遞給請求處理常式或頁面的,用以獲得jsonp回呼函數名的參數名(一般預設為:callback)jsonpCallback : "Tcallback",//自訂的jsonp回呼函數名稱,預設為jQuery自動產生的隨機函數名,也可以寫"?",jQuery會自動為你處理資料success : function(json) {alert(‘name: ‘ + json.name + ‘,age: ‘ + json.age);},error : function() {alert(‘fail‘);}});});</script></body></html>

  此段代碼相當於get請求http://127.0.0.1:8089/test2/TestServlet?id=1&callback=Tcallback .

三、伺服器實現

  伺服器端使用servlet實現,代碼如下:

public class TestServlet extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{String id = request.getParameter("id");String callback = request.getParameter("callback");//值為Tcallback String name = "zhangsan";int age = 20;String json = String.format("%s({\"name\":\"%s\", \"age\":%s})",callback, name, age);//返回的資料PrintWriter out = response.getWriter();out.print(json);out.flush();out.close();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.