【问题标题】:Problem in jQuery.getJSON in rails 2.3.5rails 2.3.5 中 jQuery.getJSON 的问题
【发布时间】:2023-03-06 22:11:01
【问题描述】:

我想使用 getJSON() 方法进行跨域检查,我正在使用以下方法

<script> jQuery.getJSON("http://localhost:3003/home/unique_email/1?email=example@gmail.cmo&callback=result", { format: "jsonp" }, function(result) { alert(result.text) }); </script>

在控制器中

def unique_email
count = User.count(:all, :conditions => ['email = ?',params[:email]] )
result = Hash.new()

if count > 0
  result[:text] = "false"
else
 result[:text] = "true"
end
respond_to do |format|
  format.json {
  render :json => result
  }
end

结束

我在同一个域中收到警报,这意味着我在我的应用程序中收到警报,但是将代码放在应用程序之外意味着我没有收到任何错误,但调用了应用程序操作..但我没有得到应用程序的任何响应。

我们将不胜感激。

感谢和问候,

拉马纳维尔·塞尔瓦拉茹。

【问题讨论】:

    标签: jquery ruby-on-rails getjson


    【解决方案1】:

    我找到了答案,

    我们需要在应用控制器中添加render_json方法。

      private
    
        # render json, but also allow JSONP and handle that correctly
        def render_json(json, options={})
          callback, variable = params[:callback], params[:variable]
          logger.debug("render json or jsonp? Callback = #{callback}, Variable=#{variable}")
          response = begin
            if callback && variable
              "var #{variable} = #{json};\n#{callback}(#{variable});"
            elsif variable
              "var #{variable} = #{json}"
            elsif callback
              "#{callback}(#{json});"
            else
              json
            end
          end
          render({:content_type => :js, :text => response}.merge(options))
        end
    

    所以我们可以在 jQuery ajax 中将 dattype 获取为 jsonp。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多