JSONP使用笔记

时间:2021-09-21 16:30:47

JSONP

  JSONP是实现跨域GET请求的一种方法, 原理上利用script标签可以动态加载JS文件,

将不同源站点的JSON数据加载到本网站来,如果给定回调函数,将回调函数名传递到服务器端,

在服务器端生成 此函数以JSON数据为入参的调用语句,就为一般AJAX实现的getJSON接口。

getJSON接口如果请求URL与当前URL一致,则为一般网站访问。

下文给出详尽的解释

http://www.cnblogs.com/yuzhongwusan/archive/2012/12/11/2812849.html

实验

jsonpServer.php

<?php
$jsondata = "{symbol:'IBM', price:120}";
echo $_GET['callback'].'('.$jsondata.')';
?>

jsonpClient.html

<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style> </style>
</head>
<body>
<h1>hello world!</h1>
<input type="text" value="test"/>
<input type="button" value="button"/>
<script type='text/javascript'>
$("[type='button']").click(function(){
//JQuery JSONP Support
var url = "http://127.0.0.1/jsonpServer.php?callback=?";
$.getJSON(url, function(data){
var retMsg = "Symbol:" + data.symbol + ", Price:" + data.price;
$("[type='text']").val(retMsg);
});
})
</script>
</body>
</html>

客户端用户访问 http://localhost/jsonpClient.html,

点击按钮,发起JSONP请求,

GET http://127.0.0.1/jsonpServer.php?callback=jQuery18305268568145111203_1403193771906&_=1403194058203 HTTP/1.1
Host: 127.0.0.1
Connection: keep-alive
Accept: */*
User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
Referer: http://localhost/jsonpClient.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8,en-GB;q=0.6,en;q=0.4

服务器端响应内容为,可见$.getJSON检测URL中有callback=?, 表示将第二个参数作为回调函数,

但是第二个函数为 匿名函数, 所以就给此函数重命名一个复杂长串, 以备响应时候触发调用。

HTTP/1.1 200 OK
Date: Thu, 19 Jun 2014 16:07:38 GMT
Server: Apache/2.4.7 (Win32) OpenSSL/0.9.8y PHP/5.4.25
X-Powered-By: PHP/5.4.25
Content-Length: 67
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html

jQuery18305268568145111203_1403193771906({symbol:'IBM', price:120})

用途:

1、 跨域数据获取,例如获取天气预报等数据。

2、 跨域提交(GET方式),提交简单地数据。