【问题标题】:JavaScript $.getJSON IssueJavaScript $.getJSON 问题
【发布时间】:2012-01-21 13:55:38
【问题描述】:

我的一段 JavaScript 代码有问题 - 下面显示了一个 sn-p。基本上,代码向 rails 控制器发出 getJSON 请求,然后应该处理返回的数据,构建 HTML 表,然后将其嵌入到 Div 中。它不起作用。我已经尝试通过警报等逐步完成它 - 一切都无济于事。数据是从 rails 控制器检索的,我可以验证这一点。我已将发出和处理 getJSON 请求的代码放在 Rails 欢迎页面的中间——这不是我的全部。代码如下:

     <!DOCTYPE html>
<html>
  <head>
    <title>Ruby on Rails: Welcome aboard</title>
    <style type="text/css" media="screen">
      body {
        margin: 0;
        margin-bottom: 25px;
        padding: 0;
        background-color: #f0f0f0;
        font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
        font-size: 13px;
        color: #333;
      }

      h1 {
        font-size: 28px;
        color: #000;
      }

      a  {color: #03c}
      a:hover {
        background-color: #03c;
        color: white;
        text-decoration: none;
      }


      #page {
        background-color: #f0f0f0;
        width: 750px;
        margin: 0;
        margin-left: auto;
        margin-right: auto;
      }

      #content {
        float: left;
        background-color: white;
        border: 3px solid #aaa;
        border-top: none;
        padding: 25px;
        width: 500px;
      }

      #sidebar {
        float: right;
        width: 175px;
      }

      #footer {
        clear: both;
      }


      #header, #about, #getting-started {
        padding-left: 75px;
        padding-right: 30px;
      }


      #header {
        background-image: url("images/rails.png");
        background-repeat: no-repeat;
        background-position: top left;
        height: 64px;
      }
      #header h1, #header h2 {margin: 0}
      #header h2 {
        color: #888;
        font-weight: normal;
        font-size: 16px;
      }


      #about h3 {
        margin: 0;
        margin-bottom: 10px;
        font-size: 14px;
      }

      #about-content {
        background-color: #ffd;
        border: 1px solid #fc0;
        margin-left: -55px;
        margin-right: -10px;
      }
      #about-content table {
        margin-top: 10px;
        margin-bottom: 10px;
        font-size: 11px;
        border-collapse: collapse;
      }
      #about-content td {
        padding: 10px;
        padding-top: 3px;
        padding-bottom: 3px;
      }
      #about-content td.name  {color: #555}
      #about-content td.value {color: #000}

      #about-content ul {
        padding: 0;
        list-style-type: none;
      }

      #about-content.failure {
        background-color: #fcc;
        border: 1px solid #f00;
      }
      #about-content.failure p {
        margin: 0;
        padding: 10px;
      }


      #getting-started {
        border-top: 1px solid #ccc;
        margin-top: 25px;
        padding-top: 15px;
      }
      #getting-started h1 {
        margin: 0;
        font-size: 20px;
      }
      #getting-started h2 {
        margin: 0;
        font-size: 14px;
        font-weight: normal;
        color: #333;
        margin-bottom: 25px;
      }
      #getting-started ol {
        margin-left: 0;
        padding-left: 0;
      }
      #getting-started li {
        font-size: 18px;
        color: #888;
        margin-bottom: 25px;
      }
      #getting-started li h2 {
        margin: 0;
        font-weight: normal;
        font-size: 18px;
        color: #333;
      }
      #getting-started li p {
        color: #555;
        font-size: 13px;
      }


      #sidebar ul {
        margin-left: 0;
        padding-left: 0;
      }
      #sidebar ul h3 {
        margin-top: 25px;
        font-size: 16px;
        padding-bottom: 10px;
        border-bottom: 1px solid #ccc;
      }
      #sidebar li {
        list-style-type: none;
      }
      #sidebar ul.links li {
        margin-bottom: 5px;
      }

    </style>

    <script src="/javascripts/jquery.js" type="text/javascript"></script>

    <script type="text/javascript">
      function about() {
        info = document.getElementById('about-content');
        if (window.XMLHttpRequest)
          { xhr = new XMLHttpRequest(); }
        else
          { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
        xhr.open("GET","rails/info/properties",false);
        xhr.send("");
        info.innerHTML = xhr.responseText;
        info.style.display = 'block'
      }
    </script>


        <script type="text/javascript">

           alert('Start of JSON Routine');

           $(document).ready( function() {

             alert('Attach a JQuery Live event to the button');

             $('#getdata-button').live('click', function() {

               alert("Get JSON data");

               $.getJSON('http://0.0.0.0:3000/getjson/1', function(data) {

                  alert('Processing returned JSON data');

                  var tmp = '<table border=1>';

                  for (i=0;i<data.length;i++)
                  {
                    tmp = tmp +'<tr>';
                      tmp = tmp + '<td>' + data[i].book.price         + '</td>';
                      tmp = tmp + '<td>' + data[i].book.title         + '</td>';
                      tmp = tmp + '<td>' + data[i].book.author        + '</td>';
                      tmp = tmp + '<td>' + data[i].book.ISBN          + '</td>';
                      tmp = tmp + '<td>' + data[i].book.yearPublished + '</td>';
                      tmp = tmp + '<td>' + data[i].book.volume        + '</td>';
                      tmp = tmp + '<td>' + data[i].book.publisher     + '</td>';
                      tmp = tmp + '<td>' + data[i].book.edition       + '</td>';
                      tmp = tmp + '<td><a href=# onclick=\"alert('+ i +')\">View</a></td>'; 
                    tmp = tmp + '</tr>';
                  }

                  tmp = tmp + '</table>';

                  alert('About to insert Table into DOM in content Div');

                  $('#showdata').html(tmp);

               }); //getJSON        end
             });   //getdata-button end
           });     //document.ready end

           alert('End of JSON routine'); 

        </script>

  </head>



  <body>
    <div id="page">
      <div id="sidebar">
        <ul id="sidebar-items">
          <li>
            <h3>Browse the documentation</h3>
            <ul class="links">
              <li><a href="http://api.rubyonrails.org/">Rails API</a></li>
              <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li>
              <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li>
              <li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li>
            </ul>
          </li>
        </ul>
      </div>





        <a href="#" id="getdata-button">Get JSON Data</a>

        <script>alert("Before the JMC div");</script>

        <div id="showdata">JMC</div>


        <script>alert("Past the JMC div");</script>


       <div id="content">


          <h1>Welcome aboard</h1>
          <h2>You&rsquo;re riding Ruby on Rails!</h2>
        </div>

        <div id="about">
          <h3><a href="rails/info/properties" onclick="about(); return false">About your application&rsquo;s environment</a></h3>
          <div id="about-content" style="display: none"></div>
        </div>

        <div id="getting-started">
          <h1>Getting started</h1>
          <h2>Here&rsquo;s how to get rolling:</h2>

          <ol>
            <li>
              <h2>Use <code>rails generate</code> to create your models and controllers</h2>
              <p>To see all available options, run it without parameters.</p>
            </li>

            <li>
              <h2>Set up a default route and remove or rename this file</h2>
              <p>Routes are set up in config/routes.rb.</p>
            </li>

            <li>
              <h2>Create your database</h2>
              <p>Run <code>rake db:migrate</code> to create your database. If you're not using SQLite (the default), edit <code>config/database.yml</code> with your username and password.</p>
            </li>
          </ol>
        </div>
      </div>

      <div id="footer">&nbsp;</div>
    </div>
  </body>
</html>

这是我刚从浏览器直接调用 URL/Controller 操作时返回的 JSON 数据:

[
   {
      "book":{
         "price":"25.52",
         "created_at":"2011-10-27T22:35:04Z",
         "ISBN":"",
         "author":"Obie Fernandez",
         "title":"Rails 3 Way, The (2nd Edition)",
         "updated_at":"2011-10-27T22:35:04Z",
         "yearPublished":"2010",
         "id":1,
         "publisher":"Addison-Wesley",
         "volume":"2",
         "edition":"second edition"
      }
   },
   {
      "book":{
         "price":"23.94",
         "created_at":"2011-10-27T22:39:37Z",
         "ISBN":"",
         "author":"Michael Hartl",
         "title":"Ruby on Rails 3 Tutorial: Learn Rails by Example",
         "updated_at":"2011-10-27T22:39:37Z",
         "yearPublished":"2010",
         "id":2,
         "publisher":"Addison-Wesley",
         "volume":"",
         "edition":"first edition"
      }
   },
   {
      "book":{
         "price":"24.97",
         "created_at":"2011-10-27T22:42:42Z",
         "ISBN":"",
         "author":"Cloves Carneiro Jr. and Rida Al Barazi",
         "title":"Beginning Rails 3 ",
         "updated_at":"2011-10-27T22:42:42Z",
         "yearPublished":"2009",
         "id":3,
         "publisher":"Apress",
         "volume":"",
         "edition":"first edition"
      }
   }
]

任何其他可能有用的东西。 Rails 日志显示请求被正确处理。

当我单步执行脚本时,警报会按顺序出现:

我收到的第一个警报是“在 JSON 例程开始时”,然后是“完成文档准备例程”,然后是“将 JQuery Live 事件附加到按钮”。然后我单击 getdata 按钮,然后在 URL 的末尾出现一个 #,然后什么也没有。

将脚本移动到头部 - 结果相同。

将#content 切换为#showdata - 结果相同。

最终编辑:

多亏了很多人的投入,问题才得以解决。

有很多问题,但最后一个问题是同源错误,因为 getJSON 请求上的 URL 与发出请求的 URL 不同。请求有 0.0.0.0:3000/getjson/1,而请求 URL 是 localhost:3000/getjson/1。很难发现,并且 getJSON 缺少返回/状态信息使其更加困难。无论如何,感谢所有贡献者,他们都做出了有效的贡献。我希望有一天我有专业知识为自己做出贡献。

【问题讨论】:

  • @MikeStewart "数据是从控制器中检索到的 [...]"
  • 你能给我们举一个你的json数据的例子吗?你有任何错误吗?究竟什么不是“工作”?
  • 也许脚本标签正在替换自己,把代码放在头上试试?该脚本包含在#content
  • 您在此处缺少一个分号:alert('About to insert Table into DOM in content Div')
  • 您的代码有效:jsfiddle.net/gilly3/RtCaB.

标签: javascript jquery ruby-on-rails ruby-on-rails-3 json


【解决方案1】:

$('#content') 似乎不存在。

编辑

再看一遍,问题似乎在于按钮click 事件未触发。由于这是通过live 添加的,并且正如另一位用户发布的那样,适用于 jsfiddle:我想知道您使用的是什么版本的 jQuery?看起来它确实可能很老了。尝试升级到新版本。

【讨论】:

  • 哈哈。树木为木。虽然 - 在那种情况下,它试图取代自己。 @JoeMcGouran:尝试将 $('#content').html(tmp); 更改为 $('#content').append(tmp);
  • 试过了 - 似乎没什么区别。
  • 以不同的方式实现相同事物的任何方式 - 更少的嵌套方式。任何想法。
  • 正如 OP 不断尝试说(通过编辑此答案)jquery 版本是 1.7.1
  • 对不起,@JonEgerton,我不明白。我在此页面上的任何地方都看不到对 jquery 版本号的任何引用。
【解决方案2】:

这与同源策略(跨域阻止)最相关,可以通过使用 JSONP 调用来解决。在网址末尾添加?callback=?

    $(document).ready( function() { 
         alert('Attach a JQuery Live event to the button'); 
         $('#getdata-button').live('click', function() { 
           $.getJSONP('http://0.0.0.0:3000/getjson/1?callback=?, function(data) { 

             // ... Omiting for brevity

              $('#content').html(tmp); 

           }); 
         }); 
       }); 

【讨论】:

  • 或在响应中添加 access-control-allow-origin 标头
  • 设置是我在一台机器上使用本地主机和浏览器、WebBrick 服务器和 Rails 服务器。
  • 将脚本移到内容 Div 上方 - 同样的问题。
  • 您会推荐哪个版本。目前有我作为 Gem 安装指令 gtom Github 站点的一部分安装的版本。感谢您回来 - 查看最新版本的代码。在 JSFiddle 中,他模拟了 getJSON 连接 - 不幸的是,这并不等同。
  • 为什么我会收到跟踪警报等,现在该功能位于 Head 部分。我认为那里的一个函数只有在调用时才会触发。
【解决方案3】:

您的页面正在刷新,数据可能会被丢弃。试试:

$('#getdata-button').live('click', function(evt) {
  evt.preventDefault();     
}

【讨论】:

  • 试过了 - 没有任何区别。是否有任何其他方法可以重组代码以实现获取和处理 JSON 数据的相同目标 - 假设 rails 应用程序暂时不是问题。
  • 页面上一定还有一个错误。 preventDefault 将解决您“单击获取数据的按钮,然后在 URL 的末尾出现 #,然后什么也没有”的问题。您至少应该收到errorsuccess 警报。如果没有,请尝试在您的 ajax 调用中设置 timeout: 5000
  • Brett - 右大括号后是否应该有右括号。问题在于 getJSON 函数挂起,即使服务器正在发回 HTTP 代码 200 回复。但是,每一点都有帮助 - 非常感谢。
【解决方案4】:

好吧,Joe,您需要从最简单的情况开始...清理所有 HTML 并删除所有您不需要的内容。我对此进行了测试并确认它可以在我的本地 Rails 服务器上运行。

我使用以下方法模拟了 Rails 控制器操作以返回您的 JSON 数据:

  def getjson
    json_data = '[{ "book": { "price": 18.75, "title": "Moby Dick", "author": "Herman Melville", "ISBN": "0393972836", "yearPublished": 2001, "volume": 1, "publisher": "W. W. Norton & Company", "edition": "2nd Edition" }}]'
    render :json => json_data, :status => :ok
  end

您不需要更改 Rails 控制器代码,因为您说它可以工作。我只是想向您展示我是如何模拟它的,以供您将来参考。

现在,将 HTML 文件的内容替换为:

<!DOCTYPE html>
  <html>
    <head>
      <title>JSON Test example</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

      <script type="text/javascript">
        $(document).ready(function() {

            $('#getdata-button').live('click', function() {
                // clear out the old data:
                $('#content').html('');

                alert("Getting JSON data");

                $.ajax({
                    dataType: 'json',
                    type: 'GET',
                    url: '/getjson/1',
                    success: function(json) {
                        console.log(json);
                        alert('Processing returned JSON data');

                        var tmp = '<table border=1>';

                        for (i = 0; i < json.length; i++) {
                            tmp = tmp + '<tr>';
                            tmp = tmp + '<td>' + json[i].book.price + '</td>';
                            tmp = tmp + '<td>' + json[i].book.title + '</td>';
                            tmp = tmp + '<td>' + json[i].book.author + '</td>';
                            tmp = tmp + '<td>' + json[i].book.ISBN + '</td>';
                            tmp = tmp + '<td>' + json[i].book.yearPublished + '</td>';
                            tmp = tmp + '<td>' + json[i].book.volume + '</td>';
                            tmp = tmp + '<td>' + json[i].book.publisher + '</td>';
                            tmp = tmp + '<td>' + json[i].book.edition + '</td>';
                            tmp = tmp + '<td><a href=# onclick=\"alert(' + i + ')\">View</a></td>';
                            tmp = tmp + '</tr>';
                        }

                        tmp = tmp + '</table>';

                        alert('About to insert the following data into DOM: ' + tmp);

                        // Show the div we are looking for in the browser's console
                        console.log($('#content'));

                        $('#content').html(tmp);
                    },
                    error: function(response) {
                        alert('There was an error: ' + response.status);
                    }
                }); // $.ajax end
            }); //getdata-button end

        }); //document.ready end
    </script>
  </head>

  <body> 
    <a href="#" id="getdata-button">Get JSON Data</a>
    <br/><br/>
    <div id="content">The data will be placed here.</div>
  </body>
</html>

请注意,我正在使用$.ajax 方法,该方法允许我指定错误处理程序回调。我会建议您使用这种方式做事,直到您对 jQuery 更加熟悉并确信您可以开始使用其他 AJAX 助手。

我希望这会有所帮助!

【讨论】:

  • 我试试看,代码卡在 getJSON 调用上。为什么在控制器中使用 :status => :ok ?
  • 这是个好电话。 “成功”是相对的——你需要真正得到回应。
  • 从我的实现中得到一个错误。错误状态码 0。
  • 如果出现 javascript 错误警报,这意味着您的控制器中有错误。我使用:status =&gt; :ok,因为它会将 HTTP 200 响应发送回浏览器。这是映射到 HTTP 状态的 Rails 状态列表:codyfauser.com/2008/7/4/…
  • 我从指南中得到了这些东西。所有 HTTP 依赖的状态一直是 200,没有失败。正如我所说,来自 response.status 属性的错误状态代码输出为 0。我很确定数据是正确的——我使用的是 Firefox 7.9.1。 - 有什么我可以做的吗,任何设置等,你想让我检查一下。鉴于设置是在我的笔记本电脑上,如果这是相同的来源政策问题,我会感到惊讶。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
  • 1970-01-01
相关资源
最近更新 更多