跨域AJAX的Restler回调参数


Luracast Restler callback parameter for cross-domain AJAX

我使用Restler实现一个简单的REST API。现在,如果我需要通过AJAX从另一个域使用该API,我将需要在发送请求时发送回调参数。Restler中对此是否有支持(我还没有找到任何真正的文档)?

对于任何从google来到这个页面的人,我在github上提交了一个问题,并得到了作者的大力支持。如果您熟悉Restler是如何构建的,那么实现起来相当简单。

从https://github.com/Luracast/Restler/issues/17

<?php
//jsonpformat.php
class JsonpFormat implements iFormat {
    const MIME = 'text/javascript';
    const EXTENSION = 'js';
    /*
     * JsonFormat is used internally
     * @var JsonFormat;
     */
    public $jsonFormat;
    public static $functionName = 'parseResponse';
    public function __construct() {
        $this->jsonFormat = new JsonFormat ();
        if (isset ( $_GET ['jsonp'] )) {
            self::$functionName = $_GET ['jsonp'];
        }
    }
    public function getMIMEMap() {
        return array (self::EXTENSION => self::MIME );
    }
    public function getMIME() {
        return self::MIME;
    }
    public function getExtension() {
        return self::EXTENSION;
    }
    public function encode($data, $human_readable = FALSE) {
        return self::$functionName . '(' . $this->jsonFormat->encode ( $data, $human_readable ) . ');';
    }
    public function decode($data) {
        return $this->jsonFormat->decode ( $data );
    }
    public function setMIME($mime) {
        //do nothing
    }
    public function setExtension($extension) {
        //do nothing
    }
}
?>

应该保存在与restler.php文件相同的目录中。有了这些文件之后,编辑您的网关(index.php)以包含该文件,并将其添加为受支持的格式。例子:

<?php
require_once '../../restler/restler.php';
#set autoloader
#do not use spl_autoload_register with out parameter
#it will disable the autoloading of formats
spl_autoload_register('spl_autoload');
$r = new Restler();
$r->setSupportedFormats('JsonpFormat','JsonFormat', 'XmlFormat');
$r->addAPIClass('BMI');
$r->handle();
?>

这对我们来说很有效:标题("Access-Control-Allow-Origin: *");

在返回单个端点之前将其添加到控制器方法中,添加到该分支或更高分支中所有端点的控制器类构造函数中,以允许它在整个站点范围内使用。

如果你只允许某些网站访问使用header(' access - control - allow - origin: example.com')或类似header(' access - control - allow - origin: ')。remote_domain美元)。其中$remote_domain是根据传入的令牌或类似的东西动态设置的。查看跨域资源共享(CORS)了解为什么要限制*通配符的使用。

<?php
class Say {
__construct(){
  header('Access-Control-Allow-Origin: *'); //Here for all /say
}
function hello($to='world') {
   header('Access-Control-Allow-Origin: *'); //Here for just /say/hello 
   return "Hello $to!";
  }
}

上面的操作适用于GET和POST,其他操作需要restler提供一些额外的头信息。下面是一些例子:

header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS');

对于IE9及以下版本,您将需要一个JSONP hack。Restler有一个扩展iFormat类来包装API输出JASONP样式的例子。

查看Mozilla hack关于CORS的细节。http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/看看PHP REST API中的OPTIONS

我在这里补充一下,如果出于某种原因不想使用JSONP,您可以简单地添加:

header('Access-Control-Allow-Origin: *');

根据punkael的第一个答案(他没有指定在雷斯特中做什么)。将这一行添加到Restler .php的sendData($data)函数中,Restler将头数据添加到响应中。从第378行开始。

但是要小心,因为这将允许任何域从您的API获取数据。