如何使用 PHP/JQuery/JSONP 动态进行回调(Laravel 项目)

use*_*337 5 javascript php jquery callback laravel-4

现在我正在开发一个小部件,我希望某些人将其放在他们的网站上,该小部件将向他们发送信息并获取一些信息。现在,我让他们在代码中使用以下内容:

<script src="http://myurl.com/widget/widgetscript.js" type="text/javascript"></script>
<div id="example-widget-container"></div>
Run Code Online (Sandbox Code Playgroud)

在 widgetscript.js 中,我有以下内容:

var jsonp_url = "http://myurl.com/widget/external_widget?callback=?";
$.getJSON(jsonp_url, function(data) {
    $('#example-widget-container').html("This data comes from another server: " + data.msg);
});
Run Code Online (Sandbox Code Playgroud)

这里调用的路由调用我的 WidgetController.php 中的一个函数:

public function external_widget($id) {

    $array = Fan::likes_by_city($id);

    $data = "{msg:'Hello World!'}";

    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;
    }
Run Code Online (Sandbox Code Playgroud)

我希望这个函数是动态的,这样我就可以为每个使用该小部件的用户定制该函数中的数据(将 $id 作为参数)。我知道我可以用我的路线来做到这一点,如下所示:

Route::get('/widget/external_widget/{id?}', array('uses' => 'WidgetController@external_widget'));
Run Code Online (Sandbox Code Playgroud)

只需将 id 参数添加到 url 中即可。

但是,在放置在用户端的代码(脚本和 div)中,我看不出有什么办法可以使其动态化。有没有办法从脚本或 div 获取 id 数据,从而更改 widgetscript.js 并从而更改调用的路由?感谢您的帮助。

Hug*_*ing 5

您可以像任何请求一样执行此操作:将参数添加到 url 中以自定义请求。

一个简单的示例是将widgetscript.js脚本更改为如下所示:

//create a function for your widget. 
//In javascript a function is also a class and this keeps all your variables and settings within your own scope so you dont have to worry about other scripts

//Keep in mind that I do some basic error checking, but not much.
//If you dont check for errors and a user provides wrong information he might get JS errors on his site.
//If you want to have a user friendly widget, make sure you check as much as possible and provide usefull information about the problems.

function MyCoolWidgetClass() {
  //In javascript it is possible to alter the reference to this, EG: using apply
  //To make sure you can always reference your own class, store the reference.
  var self = this;

  //define the basic settings
  self.defaultSettings = {
    container: '#example-widget-container',
    title: "Widget result",
    background: "#ccc",
    userId: 0
  }

  self.settings = {};

  //start your widget
  self.start = function(options) {  
    //merge the provided settings with the default settings
    $.extend(self.settings, self.defaultSettings, options);

    //check if the userid is provided
    //you could add more checks to validate the userId
    if (self.settings.userId==0) {
      alert("We need to know who you are");
      return;
    }

    var jsonp_url = "http://myurl.com/widget/external_widget?userId="+self.settings.userId+"&callback=?";
    $.getJSON(jsonp_url, function(data) {
        //create the response
        //This is just to show how you could use the settings to show a title or anyting else.
        //Again, you could check if the settings are correct.
        var html = '<div class="title">'+self.settings.title+'</div><div class="content" style="background:'+self.settings.background+'">'+data.msg+'</div>';

        //add it to the provided container
        //keep in mind that a user could provide a container like '.items' or 'div' and then it will be added to multiple instances
        $(self.settings.container).html(html);
    });
  }
}
//create a globally approachable instance of your class
window.MyCoolWidget = new MyCoolWidgetClass();
Run Code Online (Sandbox Code Playgroud)

现在,用户可以将您的小部件添加到他的网站并提供一些选项。

<script src="http://myurl.com/widget/widgetscript.js" type="text/javascript"></script>
<script>
$(function(){
  //notice that I dont provide a background, and thus the default will be used.
  MyCoolWidget.start({title: "Another title", container: "#mywidgetcontainer", userId: 10});
});
</script>
<div id="mywidgetcontainer"></div>
Run Code Online (Sandbox Code Playgroud)

现在我不确定您的响应是什么,但在大多数情况下,不建议简单地使用实际的用户 ID。人们可以简单地使用另一个号码来检查其他人的响应。

由于每个人在访问您的网站(小部件所在的网站)时都可以查看 JS 代码,因此您永远无法真正阻止人们使用其他人的 ID,但如果 ID 是一个长随机区分大小写的密钥,至少他们无法猜测其他帐户滥用您的服务。例如,如果您的每个 ID 每天的请求限制为 1000 个。

JSFiddle 使用此小部件显示您的 IP 地址