您的位置:首页 > Web前端 > JavaScript

ajax, json, jsonp, restful的区别

2013-09-03 09:44 465 查看
Ajax, or more properly, AJAX, stands for Asynchronous Javascript And Xml. Technically it refers to any asynchronous request made by the browser (anything that uses an
XmlHttpRequest
) on behalf of some script running on the current page, regardless of what content-type is returned. It can also be used to describe a certain pattern of constructing a page/site where most/all of the content is fetched/updated dynamically
on the page. When used to describe a data format, "ajax" typically means "xml".

JSON is a data encoding format. The name itself is an acronym for "JavaScript Object Notation". JSON-formatted data looks like:

{"key": "value1", "key2": {"number": 1, "array": [0, 1, 2]}}

JSON data may be fetched by an AJAX request, though it is quite commonly used in other contexts as a lightweight, extensible, and easy-to-parse data exchange format.

JSONP is simply JSON-formatted data wrapped in a callback function. The "P" stands for "with Padding", which is kind of stupid unless you like to think of function calls as "padding". In any case, JSONP data will look like:

someFunction({"key": "value1", "key2": {"number": 1, "array": [0, 1, 2]}});

As such, JSONP is really just a JavaScript snippet, and unlike JSON is not used outside of the context of JavaScript, browsers (or other JavaScript-capable clients), and AJAX requests. The reason for using JSONP is that it allows the
same-origin policy to be subverted. A script that was sourced in from site X cannot make a direct request to site Y if site Y is on a different domain from site X. But if site Y's
server can send JSONP-formatted responses, then the script from site X can add a new
<script>
tag to the document that references a URL on site Y, and when the response from site Y is loaded it will invoke some callback function that script X has defined in the document, thus giving script X access to data that was loaded dynamically
from site Y.

Note that JSONP data is not (typically) requested using an
XmlHttpRequest
. It can be done this way, subject to the standard caveats of the same-origin policy, but then you lose the cross-domain magic that makes JSONP useful in the first place.

REST is simply the formal spec/description of how HTTP actually works/is intended to be used. If you understand the concept of a URL being used to request a corresponding resource from a server and the difference between
Get
and
Post
then you really know all you need to about REST.

///未完待续..........

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: