【问题标题】:Jquery Ajax request to Sinatra app对 Sinatra 应用程序的 Jquery Ajax 请求
【发布时间】:2012-10-23 22:58:23
【问题描述】:

我已经有一段时间了,但我错过了一些东西。我刚刚设置了一个返回 JSON 的简单 Sinatra 应用程序:

get '/json' do
  content_type :json
  $data.to_json
end

这工作正常,然后我用来做跨域请求的 javascript 是

$.getJSON("http://domain.com/json?callback=?", function(data) {
   console.log(data);
});

不幸的是,我只是在控制台Uncaught SyntaxError: Unexpected token : 中不断收到错误消息,尽管我尝试了仅使用$.ajax 方法,但我仍然得到相同的结果。

这是我的服务器或客户端代码上的错误吗?任何帮助表示赞赏。

【问题讨论】:

  • $data 是从几个不同来源编译值的哈希值。
  • 哦,对不起,我的意思是,你从哪里得到这个错误? :)
  • 通过 Chrome 中的控制台
  • 我认为这是服务器端的错误。 json肯定有问题。您还可以检查使用不带参数的回调是否也会引发错误。它不应该。哈希一定有问题。
  • 当 json 出现问题时,一个有用的事情是通过网络上的任何 json lint thingies 运行返回的 json。 (谷歌“json lint”)

标签: javascript jquery ruby ajax sinatra


【解决方案1】:

您提到您正在发出跨域请求。对于 JSONP,您需要包装 json 响应以模拟函数调用。有一个Sinatra helper,这很容易。

【讨论】:

  • 感谢 kxb。以为我不需要 3rd 方库,但这成功了。
  • 只是一个注释。虽然它可以工作,但返回的数据是一个字符串,然后需要将其转换为带有data: jQuery.parseJSON(data) 的 JSON 对象,以便在其他函数中使用。
【解决方案2】:

此处使用不同端口的工作示例

Ruby 与 Sinatra

require 'rubygems'
require 'sinatra'
require "sinatra/jsonp"

get '/note/all/' do
  data = ["hello","hi","hallo"]
  JSONP data      # JSONP is an alias for jsonp method
End

在 apache 上托管的 HTML

<head id="Head1" runat="server">
    <title> English </title>
    <link href="Styles/Site.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        // to update alternative address
        $('#Updateprofile').click(function () {
        var key = "nickname"
            var details = $('#nickname').val();
        $.ajax({
            type: 'GET',
            url: 'http://localhost:4567/note/all/',
            crossDomain: true,
            data: '',
            dataType: 'jsonp',
            success: function(responseData, textStatus, jqXHR) {
            $('#controlstatus').html(+responseData);
            },
            error: function (responseData, textStatus, errorThrown) {
            alert('POST failed.'+textStatus);
            }
        });
        });
    });
</script>
</head>
<body>
    <form id="mstform" method="post" runat="server">
<input id="nickname" type="text" style="border: thin solid #C0C0C0; background-color: #EFEFEF;
        width: 300px;" />
   <br />
    <br />
    <img alt="update" id="Updateprofile" src="images/save.png" title="Clicking this button will update your profile" />
   <br />
    <br />
<div id="controlstatus"> details should be here
</div>
    </form>
</body>

【讨论】:

    猜你喜欢
    • 2013-06-06
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多