使用jsonp在ajax上呈现部分作为小部件。

时间:2022-10-08 13:08:06

I've looked at quite a few other answers on here, but I'm still struggling a bit to figure out how to set up my Rails widget.

我在这里已经看了很多其他的答案,但是我还在努力弄清楚如何设置我的Rails小部件。

I have this code in my widget controller:

我在小部件控制器中有这个代码:

  def widget
    status = Company.friendly.find(params[:id]).widget.active
    body = to_json_value(render_to_string('companies/_widget', locals: { profile: self.profile }))

    respond_to do |format|
      format.js { render json: { status: status, html: body }, callback: params[:callback] }
    end
  end

  private

  def to_json_value(str)
    str.gsub!("\"", "\\\"")
    str.gsub!(/\n+/, " ")
    str
  end

The self.profile method just sets up a list of variables that get passed to the partial.

自我。profile方法只是设置了一个被传递给部分的变量列表。

What I want to do is give a user a Javascript script tag that they can embed on their (external) website. When a user hits that page, the script will make an AJAX call to the widget controller and if the widget is turned on, it will receive a string of html to be rendered on the page.

我想做的是给用户一个Javascript脚本标签,让他们可以嵌入到他们的(外部)网站上。当用户点击该页面时,脚本将向小部件控制器发出AJAX调用,如果小部件打开,它将接收到在页面上呈现的一系列html。

So far I've got the widget controller to return a json object with the status and the html string. The problem is when I paste the localhost url into jsonlint.com, it says it is invalid. This is also confirmed when I insert a script tag into an html file and then open it in Chrome. I get an error saying there was an unexpected token :. So I then changed my controller and widget.js.erb to include a callback function. I added , callback: params[:callback] to my controller.

到目前为止,我已经获得了小部件控制器以返回一个具有状态和html字符串的json对象。问题是当我将localhost url粘贴到jsonlint.com时,它说它是无效的。当我将一个脚本标签插入到一个html文件中,然后在Chrome中打开它时,这也得到了确认。我得到一个错误,说有一个意外的令牌:。然后我改变了控制器和widget.js。erb包含一个回调函数。我添加了回调:params[:回调]到我的控制器。

I also set up a callback function (doesn't do anything yet) in my widget.js.erb file. I then embed this file using a script tag in an html file and load that in Chrome. When I do, I get an error saying that showWidget is undefined.

我还在widget.js中设置了一个回调函数(现在还没有做任何事情)。erb文件。然后,我在html文件中使用脚本标签嵌入这个文件,并在Chrome中加载它。当我这样做时,我得到一个错误,说showWidget没有定义。

I'm struggling to find resources that explain how to load data over jsonp from a rails app, and how callback functions come into play.

我正在努力寻找能够解释如何从rails应用程序中加载数据的资源,以及回调函数如何发挥作用。

Here is my widget.js.erb:

这是我widget.js.erb:

function showWidget();

$.ajax({
  type: 'GET',
  url: 'http://localhost:3000/<%= params[:company] %>/widget?callback=?',
  jsonpCallback: 'showWidget',
  contentType: "application/json",
  crossDomain: true,
  dataType: 'JSONP',
  success: function (data) {
    var result = JSON.parse(data);
    $('#company-widget').html(result.html);
  },
  error: function(e) {
    console.log(e.message);
  }
});

Here is my test.html:

这是我test.html:

<div id="company-widget"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script src="http://localhost:3000/taco-corp/widget.js?callback=showWidget" type="text/javascript"></script>

I'm also not sure where this widget.js.erb script should live in my rails app. Here is what I have so far for my widget.js.erb:

我也不知道这个widget.js在哪里。erb脚本应该生活在我的rails应用程序中。

1 个解决方案

#1


0  

I figured out what the problem was. I needed to add a callback to my rails controller and to my $.ajax method. I didn't have the callback set up correctly in my ajax call. I also needed to specify the correct header (contentType) to get around an HTTP 406 error. Here is the working jQuery code below for reference:

我弄明白了问题所在。我需要添加一个回调到我的rails控制器和我的$。ajax方法。我在ajax调用中没有正确设置回调。我还需要指定正确的头(contentType)来绕过HTTP 406错误。下面是工作的jQuery代码,供参考:

$(document).ready(function(){
    var company = 'taco-corp';

    $.ajax({
        type: 'GET',
        url: 'http://localhost:3000/' + company + '/widget.js?callback=?',
        contentType: "application/javascript",
        crossDomain: true,
        dataType: 'JSONP',
        success: function(data) {
            $('#company-widget').html(data.html);
        },
        error: function(e) {
            console.log(e.message);
        }
    });
});

And here is my rails controller:

这是我的rails控制器:

  def widget
    status = Company.friendly.find(params[:id]).widget.active

    body = render_to_string('companies/_widget', layout: false, locals: { profile: self.profile })

    respond_to do |format|
      format.js { render json: { status: status, html: body }, callback: params[:callback] }
    end
  end

#1


0  

I figured out what the problem was. I needed to add a callback to my rails controller and to my $.ajax method. I didn't have the callback set up correctly in my ajax call. I also needed to specify the correct header (contentType) to get around an HTTP 406 error. Here is the working jQuery code below for reference:

我弄明白了问题所在。我需要添加一个回调到我的rails控制器和我的$。ajax方法。我在ajax调用中没有正确设置回调。我还需要指定正确的头(contentType)来绕过HTTP 406错误。下面是工作的jQuery代码,供参考:

$(document).ready(function(){
    var company = 'taco-corp';

    $.ajax({
        type: 'GET',
        url: 'http://localhost:3000/' + company + '/widget.js?callback=?',
        contentType: "application/javascript",
        crossDomain: true,
        dataType: 'JSONP',
        success: function(data) {
            $('#company-widget').html(data.html);
        },
        error: function(e) {
            console.log(e.message);
        }
    });
});

And here is my rails controller:

这是我的rails控制器:

  def widget
    status = Company.friendly.find(params[:id]).widget.active

    body = render_to_string('companies/_widget', layout: false, locals: { profile: self.profile })

    respond_to do |format|
      format.js { render json: { status: status, html: body }, callback: params[:callback] }
    end
  end