JavaScript:如何创建JSONP? [英] JavaScript: How do I create JSONP?
问题描述
我有两个域,example1.com和example2.com
从example1.com,我想调用我在example2.com上的JSON API。知道这是不允许的,它发生在我 - 这正是为什么JSON P 创建。
问题是,如何修改
基本上,我如何创建回调api? strong> UPDATE
我的服务器端语言是PHP
很简单。只需在GET中接受一个名为 callback
的参数。
然后将回调JavaScript函数包裹在您的数据中。 p>
PHP中的示例:
<?php
$ data ='{}'; // json string
if(array_key_exists('callback',$ _GET)){
header('Content-Type:text / javascript; charset = utf8');
header('Access-Control-Allow-Origin:http://www.example.com/');
header('Access-Control-Max-Age:3628800');
header('Access-Control-Allow-Methods:GET,POST,PUT,DELETE');
$ callback = $ _GET ['callback'];
echo $ callback。'('。$ data。');';
} else {
// normal JSON string
header('Content-Type:application / json; charset = utf8');
echo $ data;
}
它的想法是简单地返回一个JavaScript文件,调用回调函数JSON对象作为JavaScript回调函数的第一个参数。
您可以使用内置的 json_encode()
函数创建JSON字符串(其中 $ data
在我们的例子中包含)从PHP中的数组和对象。
要使用JSONP服务,您可以使用< script>
标记:
< script>
function receiver(data){
console.log(data);
}
< / script>
< script src =data-service.php?callback = receiver>< / script>
I have a two domains, example1.com and example2.com
From example1.com, I would like call a JSON API I have on example2.com. Knowing that this is not allowed, it occurred to me - this is exactly why JSONP was created.
Question is, how do I modify my JSON API to make it JSONP capable?
Basically, how do I create the callback api?
UPDATE
My server side language is PHP
It is simple. Simply accept a parameter called callback
in the GET.
Then wrap the callback JavaScript function around your data.
Example in PHP:
<?php
$data = '{}'; // json string
if(array_key_exists('callback', $_GET)){
header('Content-Type: text/javascript; charset=utf8');
header('Access-Control-Allow-Origin: http://www.example.com/');
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
$callback = $_GET['callback'];
echo $callback.'('.$data.');';
}else{
// normal JSON string
header('Content-Type: application/json; charset=utf8');
echo $data;
}
It's idea is to simply return a JavaScript file which calls the callback function with the JSON object as the first parameter of the JavaScript callback function.
You can use the built-in json_encode()
function to create JSON strings (which $data
in our example above contains) from arrays and objects in PHP.
To use the JSONP service, you can use the <script>
tag:
<script>
function receiver(data){
console.log(data);
}
</script>
<script src="data-service.php?callback=receiver"></script>
这篇关于JavaScript:如何创建JSONP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!