【问题标题】:getJSON with jquery使用 jquery 获取 JSON
【发布时间】:2012-01-19 22:18:37
【问题描述】:

当我尝试使用 getJSON 显示数据时,没有任何反应,$('#child-left-container-2') 应该显示来自 php 文件的数据。我哪里出错了?...下面是我的代码的简短示例。

php 文件

while($row = mysql_fetch_assoc($query)) {

//code

    $array[] = "<div class='array-container-2' $style id='$id' data-sid='$sid' data-user='$user'>$details1</div>";


            }

            echo json_encode($array);

jquery

$(function() {
    $('.next_button').click(function() {

var id =  $('#container').find('.graphic-blank:visible').siblings().attr('id');

        $.getJSON('fetchstack.php?id='+id,function(data) {

            $('#child-left-container-2').html(''); //clear div

            $.each(data,function(i,result) {
                $('#child-left-container-2').append(result);
            });
        });

          });
});

【问题讨论】:

  • data 对象上尝试 console.log() 看看是 dom 插入还是 json get 有问题
  • 检查萤火虫控制台的错误...
  • 这意味着您的 PHP 脚本中有错误,并且您没有收到 JSON 响应。

标签: php jquery json


【解决方案1】:

我不知道这是否能解决您遇到的问题,但这就是我解决这个特定问题的方法。 试试这个代码,如果它有效,停止通过 json 发送 html 将是一个奖励。

$key = 0;
while($row = mysql_fetch_assoc($query)) {
    //code
    $array[$key]['id']      = $id;
    $array[$key]['sid']     = $sid;
    $array[$key]['user']    = $user;
    $array[$key]['content'] = $details1;
    $array[$key]['style']   = $style;
    $key++;
}

echo json_encode($array);

JS:

$(function() {
    $('.next_button').click(function() {

        var id =  $('#container').find('.graphic-blank:visible').siblings().attr('id');
        $.getJSON('fetchstack.php?id='+id,function(data) {
            $('#child-left-container-2').html(''); //clear div

            for (var i in data){
                var id      = data[i].id;
                var sid     = data[i].sid;
                var user    = data[i].user;
                var content = data[i].content;
                var style   = data[i].style;
                $('#child-left-container-2').append($('<div />').addClass('array-container-2')attr('id', id)
               .attr('data-sid', sid).attr('data-user', user).html(content);
            }           
       });
   });
});

我承认不知道 $style 是什么或它会如何呈现,我无法将它添加到链中。如果您发布 $style 的内容,我可以更新 anwser。 我希望这会有所帮助。

【讨论】:

  • 提问者必须试试这个。
【解决方案2】:

在你的 jQuery 的第二行

var id =  $('#container').find('.graphic-blank:visible').siblings().attr('id');

您正在尝试访问 jQuery 对象数组(siblings())的 id 属性。您需要指定一个 jQuery 对象来获取 $getJSON 函数的 id

更新如果只有一个同级,则通过执行指定这一点

var id =  $('#container').find('.graphic-blank:visible').siblings().eq(0).attr('id');

【讨论】:

    【解决方案3】:

    我完全没有侮辱你的意思,但你的做法是不好的做法。如果您从客户端创建 HTML,您可以有更短的请求。此外,如果您使用 firebug,您可以看到输出 JSON 的图表。它真的是一个漂亮的功能。您还可以检查它是否保存在 Firebug 的 DOM 部分下。祝你好运。

    【讨论】:

    • 没有被侮辱!你是对的!它可以在控制台中查看,但正如我在回答开始时所说的(这是我的解决方案),它对我来说效果很好。我使用它是因为我的应用程序位于 XCODE 项目中,因此本机应用程序没有控制台,并且我生成的所有 JSON 数据也在应用程序上查看。我非常关注我生成的 JSON,我建议所有人都这样做。而且这种不好的做法是很靠谱的!
    【解决方案4】:

    为什么不简单地在 PHP 文件中回显 HTML,然后用它填充容器?

    while($row = mysql_fetch_assoc($query)) {
        echo "<div class='array-container-2' $style id='$id' data-sid='$sid' data-user='$user'>$details1</div>";
    }
    
    $.getJSON('fetchstack.php?id='+id,function(data) {
        $('#child-left-container-2').html(data);
    });
    

    【讨论】:

      【解决方案5】:

      这是我的解决方案,完美无瑕:

      PHP:

      <?php
      
      ini_set('magic_quotes_gpc', false);
      header('Content-type: text/plain');
      
            //DB connection credentials
      $dbhost = 'hostname';
      $dbuser = 'database_username';
      $dbpass = 'database_password';
      $dbname = 'database_name';
      
      // allow cross-browser acces
      header('Access-Control-Allow-Origin: *');
      
      // query SQL
      $sql = "do your DB query SELECT what ever here";
      
        //do our thingies withouth hacks (SQL Injection, etc)
      try {
      $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
      $dbh->query("set names utf8");
      $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $stmt = $dbh->query($sql);  
      $json_export = $stmt->fetchAll(PDO::FETCH_OBJ);
      $dbh = null;
      
          // return JSON format DATA
      echo '{"items":'. json_encode($json_export) .'}'; 
      } catch(PDOException $e) {
      
          // return error
      echo '{"error":{"text":'. $e->getMessage() .'}}'; 
      }
      
      ?>
      

      HTML 列表视图:

      <div data-role="page" id="myPage"><div data-role="content" id="myContent">
             //my HTML list tag
        <ul data-role="listview" id="myList"></ul>
      </div></div>
      

      JAVASCRIPT

        //trigger script on show page
      $('#myPage').live('pageshow',function (event) {
             //get our JSON data
          $.getJSON('path_to_your_php_json_generator_file_declared_upper',function(data){
                //append our JSON data to a variable
             var json_entries = data.items;
                      //for each JSON data, append it to our list as one element
             $.each(json_entries,function(index,entry){
                 $('#myList').append('<li><a href="#">' + entry.title + '</a></li>');
                   //assuming we have a field named "title" in JSON data
             });
                   //refresh the list for layout (style) loading
             $('#myList').listview('refresh');
          });
      });
      

      这就是您在 jQuery Mobile 上使用 php 文件生成的 JSON 数据填充列表的方式。 您可以将这种脚本适配到您的 jQuery 代码中的每个 JSON 解释器,即使带有参数(id、类别等)!

      希望它对您有所帮助!

      【讨论】:

        【解决方案6】:

        试着把这个juste放在echo json_encode($array);之前。 最终发出退出调用以避免额外的输出。

        header('Content-type:application/json;charset=utf-8');
        echo json_encode($array);
        exit();
        

        【讨论】:

          【解决方案7】:

          在将响应设置为 html 元素之前,使用 console.log 对其进行调试,

          我没有看到你创建了一个 div 到 response = $('#child-left-container-2') 检查你是否有

          <div id="child-left-container-2" />
          

          并检查您的响应,可能是数组下的 json... 尝试console.log(data) 并使用 F12 打开调试器

          【讨论】:

            猜你喜欢
            • 2021-11-21
            • 2018-07-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-07-14
            • 2012-01-18
            • 2013-05-12
            • 2017-11-18
            相关资源
            最近更新 更多