JavaScript$.getJSON问题

JavaScript$.getJSON问题,javascript,jquery,ruby-on-rails,ruby-on-rails-3,json,Javascript,Jquery,Ruby On Rails,Ruby On Rails 3,Json,我对一段JavaScript代码有一个问题——下面是一个代码片段。基本上,代码是向rails控制器发出一个getJSON请求,然后应该处理返回的数据,构建一个HTML表,然后将其嵌入到一个Div中。这不起作用。我试着用提醒等方式来处理它,但都没有用。数据是从rails控制器检索的,我可以验证这一点。我已经将发出和处理getJSON请求的代码放在Rails欢迎页面的niddle中——这不全是我的。代码如下: <!DOCTYPE html> <html> <

我对一段JavaScript代码有一个问题——下面是一个代码片段。基本上,代码是向rails控制器发出一个getJSON请求,然后应该处理返回的数据,构建一个HTML表,然后将其嵌入到一个Div中。这不起作用。我试着用提醒等方式来处理它,但都没有用。数据是从rails控制器检索的,我可以验证这一点。我已经将发出和处理getJSON请求的代码放在Rails欢迎页面的niddle中——这不全是我的。代码如下:

     <!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实时事件附加到按钮”。然后我单击getdata按钮,然后在URL末尾出现一个#,然后什么也没有

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

将“内容”切换到“显示数据”——结果相同

最终编辑:

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

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

$(“#内容”)
似乎不存在

编辑


再看一眼,问题似乎在于按钮
单击
事件未触发。由于这是通过
live
添加的,并且正如另一个用户所发布的那样,在JSFIDLE上工作:我想知道您使用的是什么版本的jQuery?看起来它可能真的很老了。尝试升级到新版本。

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

    $(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); 

           }); 
         }); 
       }); 

您的页面正在刷新,数据可能会被删除。尝试:

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

好吧,乔,你需要从最简单的情况开始。。。清理你所有的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>

JSON测试示例
$(文档).ready(函数(){
$(“#获取数据按钮”).live('单击',函数()){
//清除旧数据:
$('#content').html('');
警报(“获取JSON数据”);
$.ajax({
数据类型:“json”,
键入:“GET”,
url:“/getjson/1”,
成功:函数(json){
log(json);
警报(“处理返回的JSON数据”);
var tmp='';
for(i=0;i
数据将放在这里。
请注意,我正在使用
$.ajax
方法,该方法允许我指定错误处理程序回调。我建议您使用这种方法,直到您对jQuery更加熟悉,并且确信可以开始使用其他AJAX助手为止


我希望这有帮助

@MikeStewart“数据是从控制器[…]检索的”您能给我们一个json数据的示例吗?你有什么错误吗?到底是什么“不起作用”?也许脚本标记正在替换自身,将代码放在头部并尝试?脚本包含在#content中。您在此处末尾缺少一个分号:
alert('About to insert Table into DOM in content Div')
您的代码可以工作:。或者在响应中添加一个访问控制allow origin头。设置是我在浏览器中使用localhost,WebBrick服务器和Rails服务器都在一台机器上。将脚本移到content Div上方-相同的问题。哪个版本