dtsi9484 2014-05-04 00:50
浏览 55
已采纳

使用Laravel 4.1 PHP控制器和JQuery / JSONP对外部窗口小部件进行回调

I am trying to make an external widget that will allow users on other sites to make a "vote", which I want to collect and store in my DB. I am trying to integrate this with my controllers/models in Laravel. However, when I place the javascript tag and the div on another site, the info is not being displayed. Right now I am trying to just pass simple info with jsonp. Here is the code:

WidgetController.php:

<?php

class WidgetController extends BaseController {


    public function external_widget() {


        $data = "{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;
        }
    }

}

widgetscript.js:

(function() {

    // Localize jQuery variable
    var jQuery;

    if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.11.0') {

        var script_tag = document.createElement('script');
        script_tag.setAttribute("type","text/javascript");
        script_tag.setAttribute("src","//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js");

        if (script_tag.readyState) {
          script_tag.onreadystatechange = function () { // For old versions of IE
              if (this.readyState == 'complete' || this.readyState == 'loaded') {
                  scriptLoadHandler();
              }
          };
        } else { // Other browsers
          script_tag.onload = scriptLoadHandler;
        }

         // Try to find the head, otherwise default to the documentElement
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    } else {
        // The jQuery version on the window is the one we want to use
        jQuery = window.jQuery;
        main();
    }

    /******** Called once jQuery has loaded ******/
    function scriptLoadHandler() {
        // Restore $ and window.jQuery to their previous values and store the
        // new jQuery in our local jQuery variable
        jQuery = window.jQuery.noConflict(true);
        // Call our main function
        main(); 
    }

    /******** Our main function ********/
    function main() { 
        jQuery(document).ready(function($) { 
           /******* Load CSS *******/
            var css_link = $("<link>", { 
                rel: "stylesheet", 
                type: "text/css", 
                href: "widgetstyle.css" 
            });
            css_link.appendTo('head');          

            /******* Load HTML *******/
            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.html);
            });
        });
    }

    })(); // We call our anonymous function immediately

widgetstyle.css is left blank for now.

The relevant route:

Route::get('/widget/external_widget', array('uses' => 'WidgetController@external_widget'));

Finally, I try to call this on another web page with:

    <div id="example-widget-container"></div>

The "hello world" i'm trying to print out on another website is not displaying. Any ideas what issues are going on?

  • 写回答

1条回答 默认 最新

  • duansha8115 2014-05-04 04:43
    关注

    To use JSONP technique, you should return valid JSON object with a function call wrapped around it. JSON is a collection of unordered attribute-value pairs. {Hello World!} is not a valid JSON, try to use proper JSON formatting may fix your problem.

    PHP

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

    Javascript

    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);
    });    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动