<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>浩行天下 ghSky-&#62;Blog &#187; JSON</title>
	<atom:link href="http://ghsky.com/tag/json/feed" rel="self" type="application/rss+xml" />
	<link>http://ghsky.com</link>
	<description>热衷于前端技术 (X)HTML, CSS, JavaScript</description>
	<lastBuildDate>Sat, 24 Jul 2010 09:30:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
	<atom:link rel='hub' href='http://ghsky.com/?pushpress=hub'/>
		<item>
		<title>利用 JSONP 进行 JavaScript 的跨域数据访问</title>
		<link>http://ghsky.com/2009/05/jsonp-cross-domain-data-access-with-javascript.html</link>
		<comments>http://ghsky.com/2009/05/jsonp-cross-domain-data-access-with-javascript.html#comments</comments>
		<pubDate>Thu, 21 May 2009 05:18:14 +0000</pubDate>
		<dc:creator>ghSky</dc:creator>
				<category><![CDATA[Web Develop]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[JSONP]]></category>

		<guid isPermaLink="false">http://ghsky.com/?p=266</guid>
		<description><![CDATA[原文来自：http://hpyer.cn/visit-remote-data-with-jsonp-in-javascript.html 一、基础知识 　　1、什么是 JSON：JavaScript Object Notation (JSON) 是一种轻量级、基于文本、语言无关的数据交换格式。它是从 ECMAScript 语言标准衍生而来的。JSON为轻便的表示结构化数据，定义了一小套格式化规则。以下是一个 JSON 对象的例子： { "Image": { "Width": 450, "Height": 561, "Title": "Intel Core 2 Duo", "Thumbnail": { "Url": "http://www.example.com/image/...", "Height": 125, "Width": "100" }, "IDs": [116, 943, 234, 38793] } } 　　2、什么是 JSONP：JSONP（JSON with Padding）是一个非官方的协议，它允许在服务器端集成 Script tags 返回至客户端，通过 Javascript callback 的形式实现跨域访问（这仅仅是 JSONP 简单的实现形式）。 二、JSONP 的原理 　　首先说明一下，想要使用 [...]]]></description>
			<content:encoded><![CDATA[<p>原文来自：<a href="http://hpyer.cn/visit-remote-data-with-jsonp-in-javascript.html" target="_blank">http://hpyer.cn/visit-remote-data-with-jsonp-in-javascript.html</a></p>
<p>一、基础知识</p>
<p>　　1、什么是 <a href="http://www.json.org/" target="_blank">JSON</a>：JavaScript Object Notation (JSON) 是一种轻量级、基于文本、语言无关的数据交换格式。它是从 ECMAScript 语言标准衍生而来的。JSON为轻便的表示结构化数据，定义了一小套格式化规则。以下是一个 JSON 对象的例子：</p>
<pre class="brush:js">
{
    "Image": {
        "Width": 450,
        "Height": 561,
        "Title": "Intel Core 2 Duo",
        "Thumbnail": {
            "Url": "http://www.example.com/image/...",
            "Height": 125,
            "Width": "100"
        },
        "IDs": [116, 943, 234, 38793]
    }
}
</pre>
<p>　　2、什么是 JSONP：JSONP（JSON with Padding）是一个非官方的协议，它允许在服务器端集成 Script tags 返回至客户端，通过 Javascript callback 的形式实现跨域访问（这仅仅是 JSONP 简单的实现形式）。<br />
<span id="more-266"></span><br />
二、JSONP 的原理</p>
<p>　　首先说明一下，想要使用 JSONP 来进行跨域访问，必须服务器端支持，原因后面再解释。和 AJAX 一样，JSONP 实际上也是早已存在，只是说法相对比较新颖（貌似也出来很久了，额…），而且所有做网页开发肯定都用过。为什么这么说？应为它用到的只是所有 HTML 元素中一个简单的 script 元素。看到这是不是觉得越发奇怪了？没关系，继续看下去就会茅厕（塞）顿开的，嘿嘿～来看个例子吧：<br />
<a href="http://ghsky.com/demo/090521/jsonp-demo.html" target="_blank">jsonp-demo.html</a> 文件</p>
<pre class="brush:html">
<!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>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />

</head>
<body>
    <script type="text/javascript">
    //<![CDATA
        function say(words) {
            alert(words);
        }
    //]]&gt;
    </script>
    <script type="text/javascript" src="jsonp-demo.js"></script>
</body>
</html>
</pre>
<p><a href="http://ghsky.com/demo/090521/jsonp-demo.js" target="_blank">jsonp-demo.js</a> 文件</p>
<pre class="brush:js">
var now = new Date();
say('Time is ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds());
</pre>
<p>　　运行 jsonp-demo.html 文件后，是不是看到写着“Time is XX:XX:XX”的警告框了（XX:XX:XX为你系统当前时间）？你可能会觉得这个例子很简单，没什么了不起的，甚至会在想：这和 JSONP 有关系吗？那么，我可以很肯定的告诉你：有关系！而且，这个例子实际上就是 JSONP 的原型！你也许会想到，JSONP 不是访问远程数据的吗？对，试想一下，如果 jsonp-demo.js 文件在其它域的服务器上呢？结果会不会出现问题？我也可以很负责的告诉你：不会！你可以将上面例子中的 jsonp-demo.js 更改为：http://ghsky.com/demo/090521/jsonp-demo.php?callback=say <a href="http://ghsky.com/demo/090521/jsonp-demo-php.html" target="_blank">再试一下</a>。<br />
　　现在，聪明的你应该已经明白 JSONP 到底是怎么回事了，那么，再来解释一下本节开头第一句话吧。看过 jsonp-demo.js 文件的内容，应该知道，其只是对一个函数（通常称之为：回调函数）的调用，而需要交互的数据则通过参数形势进行返回。所以通过 JSONP 访问的服务器需要提供一个可以设置回调函数名的接口，就像 http://ghsky.com/demo/090521/jsonp-demo.php?callback=say 中的 callback，所以，综上所述 JSONP 是需要服务器端的支持的。</p>
<p>附上 jsonp.php 的源码：</p>
<pre class="brush:php">
<?php
$type = isset($_GET['type']) ? $_GET['type'] : '';
$callback = isset($_GET['callback']) ? $_GET['callback'] : '';
$json = '';

if ($type == 'json') {
    $json = '{
        "Image": {
            "Width": 450,
            "Height": 561,
            "Title": "Intel Core 2 Duo",
            "Thumbnail": {
                "Url": "http://www.example.com/image/...",
                "Height": 125,
                "Width": "100"
            },
            "IDs": [116, 943, 234, 38793]
        }
    }';
} else {
    $time = date("H:i:s");
    $json = '"Time is '. "$time" . '"';
}

if (!empty($callback)) {
    $json = $callback . '(' . $json . ')';
}

print $json;
?>
</pre>
<p>三、jQuery 中的应用</p>
<p>　　自 1.2 版本起，<a href="http://jquery.com/" target="_blank">jQuery</a> 加入了对 JSONP 的支持。我们可以很容易的利用 $.getJSON() 方法（或者其它基于 $.ajax() 的方法），来跨域加载 JSON 数据。<br />
来个例子吧<a href="http://ghsky.com/demo/090521/jsonp-demo-2.html" target="_blank">jsonp-demo-2.html</a>：</p>
<pre class="brush:html">
<!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>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />

    <script type="text/javascript" src="jquery.js"></script>
</head>
<body>
    <script type="text/javascript">
    //<![CDATA
        function do_jsonp() {
            $.getJSON('http://ghsky.com/demo/090521/jsonp-demo.php?type=json&#038;callback=?',
            function(data) {
                $('#result').val('data.Image.IDs: ' + data.Image.IDs);
            });
        }
    //]]&gt;
    </script>
    <a href="javascript:do_jsonp();">Click me</a>
    <textarea id="result" cols="50" rows="5"></textarea>
</body>
</html>
</pre>
<p>　　你可能注意到上面的例子中，url 被写成了 http://ghsky.com/demo/090521/jsonp-demo.php?type=json&#038;callback=?，需要说明的是，这个问号会被 jQuery 自动替换为回调函数的函数名（如果是一个匿名函数，jQuery 会自动生成一个带时间戳的函数名）。</p>
<p>四、小结</p>
<p>　　通过本文的描述，相信你对于 JSONP 有了一个比较直观的了解，<a href="http://hpyer.cn/about" target="_blank">Hpyer</a> 也相信，你也肯定可以举一反三的写出属于你自己的代码。其实，JSONP 的实现方法并不是只有回调函数一种，还有其它方式，例如将数据赋值给一个变量等。在 Web 2.0 的总体趋势之下，JS 显得越来越重要，并成了许多网页制作者所必学的一种脚本，所以，尽情的去体会 JS 带来的乐趣吧，Enjoy it!</p>
]]></content:encoded>
			<wfw:commentRss>http://ghsky.com/2009/05/jsonp-cross-domain-data-access-with-javascript.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
