使用jsonp进行跨域访问
生活随笔
收集整理的這篇文章主要介紹了
使用jsonp进行跨域访问
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、使用場(chǎng)景
當(dāng)我們請(qǐng)求非本服務(wù)器的資源的時(shí)候,瀏覽器會(huì)禁止訪(fǎng)問(wèn),并提示不允許跨域訪(fǎng)問(wèn)。此時(shí)我們可以使用jsonp這種請(qǐng)求方式,從其他服務(wù)器獲取資源。在客戶(hù)端調(diào)用提供jsonp支持的接口,獲取jsonp格式的數(shù)據(jù)。
二、客戶(hù)端的實(shí)現(xiàn)
客戶(hù)端使用jsp,用js發(fā)送ajax請(qǐng)求,代碼如下:
<%@ 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",//傳遞給請(qǐng)求處理程序或頁(yè)面的,用以獲得jsonp回調(diào)函數(shù)名的參數(shù)名(一般默認(rèn)為:callback) jsonpCallback : "Tcallback",//自定義的jsonp回調(diào)函數(shù)名稱(chēng),默認(rèn)為jQuery自動(dòng)生成的隨機(jī)函數(shù)名,也可以寫(xiě)"?",jQuery會(huì)自動(dòng)為你處理數(shù)據(jù) success : function(json) {alert('name: ' + json.name + ',age: ' + json.age);},error : function() {alert('fail');}});}); </script> </body> </html>?
此段代碼相當(dāng)于get請(qǐng)求http://127.0.0.1:8089/test2/TestServlet?id=1&callback=Tcallback .
三、服務(wù)器實(shí)現(xiàn)
服務(wù)器端使用servlet實(shí)現(xiàn),代碼如下:
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");//值為T(mén)callback String name = "zhangsan";int age = 20;String json = String.format("%s({\"name\":\"%s\", \"age\":%s})",callback, name, age);//返回的數(shù)據(jù)PrintWriter out = response.getWriter();out.print(json);out.flush();out.close();} }轉(zhuǎn)載于:https://www.cnblogs.com/always-online/p/3859340.html
總結(jié)
以上是生活随笔為你收集整理的使用jsonp进行跨域访问的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 第30周一
- 下一篇: 龙族幻想雨具商人在哪里