40

我有两个域,example1.com 和 example2.com

从 example1.com,我想调用我在 example2.com 上的 JSON API。知道这是不允许的,我突然想到 - 这正是 JSON P被创建的原因。

问题是,如何修改我的 JSON API 以使其支持 JSONP?

基本上,我如何创建回调 api?

更新

我的服务器端语言是 PHP

4

8 回答 8

77

很简单。callback只需接受在 GET 中调用的参数。

然后将回调 JavaScript 函数包装在您的数据周围。

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()函数从 PHP 中的数组和对象创建 JSON 字符串($data在我们上面的示例中包含)。

要使用 JSONP 服务,您可以使用<script>标签:

<script>
    function receiver(data){
        console.log(data);
    }
</script>
<script src="data-service.php?callback=receiver"></script>
于 2009-11-05T03:54:36.800 回答
26

您需要一种服务器端语言,回调参数只是一个 GET 参数,您读取参数,然后将 JSON 响应包装到函数调用中,然后像这样打印它callback(jsonResponse);

我给你留下一个使用 Python 的极简示例,因为你没有提到任何服务器端语言:

import os
import cgi

form = cgi.FieldStorage()
callback = form.getvalue('callback','')

address = cgi.escape(os.environ["REMOTE_ADDR"])

json = '{"ip": "'+address+'", "address":"'+address+'"}'

#Allow cross domain XHR
print 'Access-Control-Allow-Origin: *'
print 'Access-Control-Allow-Methods: GET'

if callback != '':
  print 'Content-Type: application/javascript'
  result = callback+'('+json+');'
else:
  print 'Content-Type: application/json'
  result = json

print ''
print result

这是用于检索Zach制作的客户端 IP 地址的小型JSONP 服务的代码,它托管在Google App Engine上。

于 2009-11-05T03:54:20.283 回答
6

Mauris 已经给了你一个可行的例子。我只想补充一点,您应该检查callback参数是否存在且非空,如果不存在,则按原样返回不带括号的 json 数据。所以基本上你的 api 将是 JSON,并在callback给出时提供 JSON-P。

要使用 JSON-P 网络服务,除非您使用 YUI 或 jQuery 之类的框架,否则您可以简单地动态创建脚本节点并将其src属性设置为指向网络服务。请记住在再次重复之前从 dom 中删除该节点,因为此动态脚本节点仅供一次性使用。

于 2009-11-05T04:59:59.057 回答
4

我知道我参加聚会迟到了,并且其中一个答案中有关于代码安全性的评论。这是一篇很好的文章:

http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/

这是您应该运行的代码:

<?php header('content-type: application/json; charset=utf-8');

function is_valid_callback($subject)
{
    $identifier_syntax
      = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*+$/u';

    $reserved_words = array('break', 'do', 'instanceof', 'typeof', 'case',
      'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 
      'for', 'switch', 'while', 'debugger', 'function', 'this', 'with', 
      'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 
      'extends', 'super', 'const', 'export', 'import', 'implements', 'let', 
      'private', 'public', 'yield', 'interface', 'package', 'protected', 
      'static', 'null', 'true', 'false');

    return preg_match($identifier_syntax, $subject)
        && ! in_array(mb_strtolower($subject, 'UTF-8'), $reserved_words);
}

$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
$json = json_encode($data);

# JSON if no callback
if( ! isset($_GET['callback']))
    exit($json);

# JSONP if valid callback
if(is_valid_callback($_GET['callback']))
    exit("{$_GET['callback']}($json)");

# Otherwise, bad request
header('status: 400 Bad Request', true, 400);
于 2013-08-13T17:36:56.147 回答
3
// Adds script tag to head of the page
function addScriptToHead(source, code, type) {
    var script = document.createElement('script');
    if (type === 'js') {
        script.setAttribute('type', 'text/javascript');
    }
    if (source !== '') {
        script.setAttribute('src', source);
    }
    if (code !== '') {
        if (document.all && !window.opera)  {
            script.text = code;
        } else {
            script.innerHTML = code;
        }
    }
    document.getElementsByTagName('head')[0].appendChild(script);
}


// Callback function
function addScriptToHead(any_param) {

// do whatever needs to be done

}

//call example

addScriptToHead('http://url_to_receiver_script/index.php&param=anything', '', 'js');

/// 回调脚本应该返回回调函数的名称,即如果你在浏览器中输入

http://url_to_receiver_script/index.php¶m=anything

它应该只返回一个文本(现有处理函数的名称): addScriptToHead(any_param)

在任何浏览器中都像时钟一样工作。

于 2011-03-25T16:08:04.107 回答
2

使用 jQuery 很容易,即客户端:

  $.ajax({
        dataType: 'jsonp',
        data: "somedata="+somevalue,
        //this is very important since it's the callback we will and that allow cross domain
        jsonp: 'jsonp_callback',
        url: 'http://example2.com',
        //function we trigger on success
        success: ParseJson
         //error handling not working with jsonP
         //error: handleError
        });

function ParseJson(data)
{
for (var key in data) {
  if (data.hasOwnProperty(key)) {
    alert(key + " -> " + data[key]);
  }
}
}

并确保从服务器端获得正确的 json;
并且不要忘记返回 jsonp_callback 参数,否则它将不起作用!!!!!!!
就是这样。

于 2009-11-18T01:12:53.703 回答
0

您可以使用Simple JSON for PHP来伪造它!它简化了一切!

<?php

  include('../includes/json.php');

  $json = new json('callback', 'myCallback');

  $object = new stdClass();
  $object->FirstName = 'John';
  $object->LastName = 'Doe';
  $array = array(1,'2', 'Pieter', true);
  $jsonOnly = '{"Hello" : "darling"}';
  // Add objects to send
  $json->add('status', '200');
  $json->add("worked");
  $json->add("things", false);
  $json->add('friend', $object);
  $json->add("arrays", $array);
  $json->add("json", $jsonOnly, false);

  /*
  Expected result : 
  myCallback({
    "status": "200",
    "worked": true,
    "things": false,
    "friend": {
        "FirstName": "John",
        "LastName": "Doe"
    },
    "arrays": [
        1,
        "2",
        "Pieter",
        true
    ],
    "json": {
        "Hello": "darling"
    }
  });

  */
  $json->send();
?>
于 2015-04-27T16:58:51.253 回答
-1

这里的例子 http://www.insideria.com/2009/03/what-in-the-heck-is-jsonp-and.html 基本上

<script src=".../example2...?output=json;callback=loadit"></script>
<script>
alert( "I got this from example2 " + loadit);
</script>
于 2009-11-05T03:53:58.927 回答