1

私はしばらくこれに取り組んできましたが、何かが足りません。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

これは私のサーバーまたはクライアント側のコードのエラーですか?助けていただければ幸いです。

4

2 に答える 2

2

クロスドメインリクエストを行っているとのことですが。JSONPの場合、関数呼び出しを模倣するためにjson応答をラップする必要があります。それを簡単にするシナトラヘルパーがあります。

于 2012-11-03T19:39:37.590 に答える
1

ここでは、異なるポートを使用した作業例を示します

シナトラとルビー

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-09-28T03:03:53.920 に答える