0%

Jsonp 方式解决跨域问题

值得注意的是:
Jsonp 最终只能通过 GET 方式请求, 无法使用 POST 提交数据, 假设你定义 Type 为 post 也会转为 get 方式请求.

若您不希望通过此方式实现跨域请求, 请移步 Post not found: Access-Control-Allow-Origin 服务端解决跨域请求.

以下为具体代码实现:

客户端

1
2
3
4
5
6
7
8
9
10
$.ajax({
type: "GET",
url: "http://www.server.com/test.php",
dataType: 'jsonp',
jsonpCallback: 'jsonpCallback',
data: {'data':'222'},
success: function(data){
console.log(data);
}
});

服务器端

1
2
3
4
5
6
7
8
header('Content-Type:application/json; charset=utf-8');

$handler = $_GET['callback'];
$data = array(
'hello' => 'codezm',
'data' => $_GET['data'],
);
exit($handler . '(' . json_encode($data) . ');');