JSONP跨域獲取JSON數據
JSONP跨域獲取JSON數據
客戶端請求數據
<!doctype html>
<html>
<head>
<title>App Engine Demo</title>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div id="result">Loading...</div>
<br />
<p>add p</p>
<br />
<script>
$(document).ready(function() {
$.ajax({
async : false,
url : "https://hanotfun.appspot.com/demo",
type : "GET",
dataType : 'jsonp',
jsonp : 'callback',
success : function(data) {
$('#result').html("Hello, " + data.name);
}
});
});
</script>
</body>
</html>
服務器端必須對處理請求,不能直接返回json數據,而要用callback參數對數據進行包裝
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package myapp;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String callback = req.getParameter("callback");
if (callback != null && callback.length() > 0) {
resp.setContentType("text/plain");
resp.getWriter().println(callback + "({ \"name\": \"World\" })");
} else {
resp.setContentType("text/plain");
resp.getWriter().println("{ \"name\": \"World\" }");
}
}
}
//如果不包裝會報“Uncaught SyntaxError: Unexpected token :”錯誤
檢測到請求中包含callback參數時對返回數據進行包裝,否則直接返回json數據。
reference
Updated: 2020-12-20 11:17
Created: 2017-03-19 01:33