AJAX没有分离JSON字符串

时间:2014-06-09 20:10:32

标签: php ajax json

我使用星级系统来显示SQL的评级数据。每个可以评级的项目都有唯一的标识符变量$ id,评级表中的每个评级都有唯一标识符$ storyidr。我希望这个脚本显示:

  1. 平均评分
  2. 项目评分的次数。
  3. 这些值是可退休的,但它们一起显示在页面上,我无法看到如何分隔它们。例如,对于平均评级为4且已被评定为200次的项目。当用户通过AJAX点击数据返回时看起来像:

    • 对于' response1' 4" 200"
    • 对于' response2' 4" 200"

    我希望能够将它们分开看起来像:

    • 对于' response1' 4
    • 对于' response2' 200

    html page

       <div id="products" style="">
         <div class="rateit" data-storyidr="<?php echo $id; ?>">
         </div>
          <div class="averagevote">
            <div style="display:block;" id="response<?php echo $id; ?>"><?php echo $avgratep; ?></div><br>
             <div style="display:block;" id="response2<?php echo $id; ?>">RaTeD <?php echo $rankcount; ?> TiMeS</div>
            </div>
           </div>
       <?php endwhile; mysqli_close($connection); ?>
    
       <script type ="text/javascript"> 
          $('#currentslide .rateit').bind('rated reset', function (e) { 
              var ri = $(this); 
              var value = ri.rateit('value'); 
              var storyidr = ri.data('storyidr'); 
              ri.rateit('readonly', true); 
          $.ajax({
          dataType : 'json', 
          url: 'rate.php', 
          data: {storyidr: storyidr, value: value}, 
          type: 'POST', 
          success: function (data) { 
              $('#response'+storyidr).replaceWith('Avg rating ' + data.avg + '/5'); 
              $('#response2'+storyidr).replaceWith('Rated ' + data.cnt + ' times');
    
          }, 
               error: function (jxhr, msg, err) {
               $('#response').append('<li style="color:red">' + msg + '</li>');
          }
      }); 
       }); 
        </script>
    

    PHP

     <?PHP  
                $storyidr=$_POST['storyidr'];
            $mysqli = mysqli_connect($dbhost,$dbusername,$dbpasswd,$database_name) or die ("Couldn't connect to server.");
             if (mysqli_connect_errno($mysqli))
               {
               echo "Failed to connect to MySQL: " . mysqli_connect_error();
               }
            $sql  = "INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[storyidr]','$_POST[value]',now());"; 
            $sql .= "SELECT AVG(rank) AS avrank, COUNT(rank) AS countrank FROM ratings WHERE storyidr = $storyidr";
            if($mysqli->multi_query($sql))
            {   $mysqli->next_result();
            if ($result = $mysqli->store_result())
            { 
            $data = mysqli_fetch_assoc($result);
            $avrank = $data['avrank'];
            $countrank = $data['countrank'];
            $avrankr = round($avrank,2);
            if(is_null($avrank)){$avrank ="null";}
                      echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));
    
            }
            }
        ?>
    

2 个答案:

答案 0 :(得分:1)

您应该只使用json_encode()一次,并且只回显该函数的结果。多次执行此操作会使json失效:

    else
    {
       $results = array();
       $results['av'] = $avrankr;
       $results['cnt'] = $countrank;

       echo json_encode($results);
    }

然后,在您的JavaScript中,您可以直接访问data.avdata.cnt

$('#response'+storyidr).replaceWith('Avg rating ' + data.av +'/5'); 
$('#response2'+storyidr).replaceWith(data.cnt); 

你也可以在@barell提​​到的ajax调用中设置dataType参数,但通常jQuery会正确地解决这个问题。

修改:为了避免您遇到的undefined错误,您应该执行以下操作:

$results = array('status' => 'fail');
...
if () {
    ...

      if ($result)
      {
        $results['status'] = 'success';
        $results['av'] = $avrankr;
        $results['cnt'] = $countrank;
      }
}

echo json_encode($results);

现在,您可以先在ajax调用的成功回调中检查data.status并采取相应的措施:

success: function (data) {
   if (data.status === 'fail') {
      // show a warning message somewhere, this is just an example
      alert('No results found!');
   } else {
      $('#response'+storyidr).replaceWith('Avg rating ' + data.av + '/5'); 
      $('#response2'+storyidr).replaceWith('RaTeD ' + data.cnt + ' TiMeS'); 
   }
},

答案 1 :(得分:1)

我认为问题是你没有设置正确的标题。在php文件中,在输出之前,输入:

header('Content-type: text/json');

而且,不是写两个对象,而是将其写为数组:

echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));

现在它应该工作

然后,在您的Javascript中,您将访问以下数据:

$('#response'+storyidr).replaceWith('Avg rating ' + data.avg +'/5');
$('#response'+storyidr).replaceWith(data.cnt); // Suppose you want the count here