최고의 JSONP 자습서 튜토리얼 2024년, 이 튜토리얼에서는 JSONP 응용 프로그램,jQuery를가 JSONP를 사용하여,를 배울 수 있습니다.
이 장에서는 우리가 JSONP 지식을 소개합니다.
JSONP (패딩와 JSON)는 도메인 간 데이터를 읽도록, 그것은 다른 웹 도메인 (웹 사이트)에서 정보를 얻을 수있는 JSON "사용 모드"입니다.
왜 우리는 (JSONP) 그것에서 액세스 데이터에 특별한 기술이 다른 도메인 (웹 사이트)가 필요합니까? 이것은 동일한 원본 정책 때문이다.
출처 정책, 그것은 넷스케이프에 의해 제안 된 잘 알려진 보안 정책, 이제 모든 브라우저는 자바 스크립트가이 전략을 사용합니다 지원합니다.
http://www.w3write.com/try/ajax/jsonp.php?jsonp=callbackFunction : 고객이 액세스합니다.
JSON 데이터를 반환 할 것으로 예상 고객을 가정 해 봅시다 : "customername1", "customername2을"].
진정으로 고객의 데이터를 반환과 같이 표시됩니다 callbackFunction ([ "customername1", "customername2"]).
서버 파일 jsonp.php 코드 :
<?php header('Content-type: application/json'); //获取回调函数名 $jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']); //json数据 $json_data = '["customername1","customername2"]'; //输出jsonp格式的数据 echo $jsoncallback . "(" . $json_data . ")"; ?>
<script type="text/javascript"> function callbackFunction(result, methodName) { var html = '<ul>'; for(var i = 0; i < result.length; i++) { html += '<li>' + result[i] + '</li>'; } html += '</ul>'; document.getElementById('divCustomers').innerHTML = html; } </script>
<div id="divCustomers"></div>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>JSONP 实例</title> </head> <body> <div id="divCustomers"></div> <script type="text/javascript"> function callbackFunction(result, methodName) { var html = '<ul>'; for(var i = 0; i < result.length; i++) { html += '<li>' + result[i] + '</li>'; } html += '</ul>'; document.getElementById('divCustomers').innerHTML = html; } </script> <script type="text/javascript" src="http://www.w3write.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script> </body> </html>
위의 코드는 jQuery 코드 예제를 사용할 수 있습니다 :
<!DOCTYPE html> <html> <head> <title>JSONP 实例</title> <script src="http://apps.bdimg.com/libs/jquery/1.8.3/jquery.js"></script> </head> <body> <div id="divCustomers"></div> <script> $.getJSON("http://www.w3write.com/try/ajax/jsonp.php?jsoncallback=?", function(data) { var html = '<ul>'; for(var i = 0; i < data.length; i++) { html += '<li>' + data[i] + '</li>'; } html += '</ul>'; $('#divCustomers')(html); }); </script> </body> </html>