jQuery 无法从 Rails 3 应用程序接收数据

发布于 2025-01-07 21:40:47 字数 678 浏览 3 评论 0原文

我遇到了一个非常奇怪的情况,这让我发疯。我有一个 Rails 应用程序,它向 jQuery 发送一个简单的字符串并将其打印出来。这是我的代码:

jQuery:

    jQuery(document).ready(function() {
    jQuery('.bid a').livequery('click', function() {
        obj = jQuery(this);
        jQuery.post(obj.attr('href'), function(data) {
            alert(data)
        });
        return false;
    });
    })

Rails Controller:

def send_message
    respond_to do |format|
      format.js do
          @res_str = "nobids"
          render :json => @res_str
      end 
    end
end

像这样,它工作正常,它显示带有字符串“nobids”的警报。但是,如果我想发送任何其他字符串,比如“nobidss”,它就会失败!根本没有任何意义!

可能发生什么情况?

I'm having a very weird situation that is driving me nuts. I have a rails app that sends a simple string to jQuery and prints it out. Here is my code:

jQuery:

    jQuery(document).ready(function() {
    jQuery('.bid a').livequery('click', function() {
        obj = jQuery(this);
        jQuery.post(obj.attr('href'), function(data) {
            alert(data)
        });
        return false;
    });
    })

Rails Controller:

def send_message
    respond_to do |format|
      format.js do
          @res_str = "nobids"
          render :json => @res_str
      end 
    end
end

Like that, it works ok, it shows an alert with the string "nobids". However, if I want to send any other string, lets say "nobidss", it fails! It makes no sense at all!

What could be happening?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何其悲哀 2025-01-14 21:40:47

我犯了一个菜鸟错误!

如果渲染 :json ,则必须将响应消息转换为 json,即:@response.to_json。

另外,在 html 中,href 必须以 .json 结尾,并且在控制器中,您也必须响应 format.json。

无论如何,我无法告诉为什么它使用字符串“nobids”成功。

现在效果很好

I was making a rookie mistake!

If you render :json you have to convert the response message to json, ie: @response.to_json.

Also, in the html, the href has to end in .json, and in the controller you have to respond to format.json too.

I cannot tell why it was succeeding with the string "nobids" anyways.

It works beautifull now

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文