小库平台



欢迎您 本站地址:  
返回首页   返回编程教学   脑筋急转弯  压扁小鸟  喊麦串烧  交友会员源码  Typecho主题源码  六十甲子速查表  清朝历史  学习Foundation 

JSONP 教程

本章节我们将向大家介绍 JSONP 的知识。

Jsonp(JSON with Padding) 是 json 的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。

为什么我们从不同的域(网站)访问数据需要一个特殊的技术( JSONP )呢?这是因为同源策略。

同源策略,它是由 Netscape 提出的一个著名的安全策略,现在所有支持 JavaScript 的浏览器都会使用这个策略。


JSONP 应用

1. 服务端 JSONP 格式数据

如客户想访问 : https://www.www.fxku.cn/try/ajax/jsonp.php?jsoncallback=callbackFunction

假设客户期望返回数据:["customername1","customername2"]。

真正返回到客户端的数据显示为: callbackFunction(["customername1","customername2"])。

服务端文件 jsonp.php 代码为:

jsonp.php 文件代码

<?php header('Content-type: application/json'); //获取回调函数名 $jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']); //json数据 $json_data = '["customername1","customername2"]'; //输出jsonp格式的数据 echo $jsoncallback . "(" . $json_data . ")"; ?>

2. 客户端实现 callbackFunction 函数

<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> <html> <head> <meta charset="utf-8"> <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="https://www.www.fxku.cn/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script> </body> </html>

jQuery 使用 JSONP

以上代码可以使用 jQuery 代码实例:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JSONP 实例</title> <script src="https://cdn.static.www.fxku.cn/libs/jquery/1.8.3/jquery.js"></script> </head> <body> <div id="divCustomers"></div> <script>
$.getJSON("https://www.www.fxku.cn/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(html); });
</script> </body> </html>

小库网-更多推荐

段子精彩对子随机歌曲
吕氏春秋脑筋急转弯幽默故事
名人故事网站打包生成app文本替换工具
俄罗斯方块软件插件外语串烧
喊麦串烧抖店副业游戏音效
卡通音效孕产知识书籍心理学书籍
男生头像简约女生头像新闻文章源码
HTML5模板源码公共DNS IP地址中国各省电话区号
常用浏览器UA课本点读课本点读
网络单机游戏西游记知多少在线聊天对话生成器
杂说历史宋书汤饮类
美容茶学习React学习JSON
学习Linux学习Lua学习Django

欢迎您来到小库网!
小库提示

扫描下方二维码,访问手机版。