AJAX不是分离JSON字符串字符串、不是、AJAX、JSON

2023-09-10 14:32:04 作者:斩尽天下

我使用的星级评定系统来显示从SQL评级数据。这堪称每个项目都有独特的identifyer变量$ ID和评级TABL每个等级都有其独特identifyer $ storyidr。我想这个脚本显示:

的平均评分 的次数的项目已被评为

该值是retirevable,但他们在网页上显示在一起,我看不出要分开它们。例如,对于具有4的平均等级,并已在额定的200倍的一个项目。当用户通过AJAX点击返回的数据看起来像:

对于response14200 对于响应24200

我希望能够单独他们看起来像:

对于response14 对于响应2200

HTML页

 < D​​IV ID =产品的风格=>
     < D​​IV CLASS =rateit数据storyidr =< PHP的echo $ ID;>中>
     < / DIV>
      < D​​IV CLASS =averagevote>
        < D​​IV的风格=显示:块; ID =响应<?PHP的echo $ ID;>中>< PHP的echo $ avgratep; ?>< / DIV>< BR>
         < D​​IV的风格=显示:块; ID =响应2<?PHP的echo $ ID;>中>额定<?PHP的echo $ rankcount; ?>时报< / DIV>
        < / DIV>
       < / DIV>
   < PHP ENDWHILE; mysqli_close($连接); ?>

   <脚本类型=文/ JavaScript的>
      $('#currentslide .rateit)。绑定(额定复位',功能(五){
          变种RI = $(本);
          VAR值= ri.rateit('值');
          变种storyidr = ri.data('storyidr');
          ri.rateit(只读,真正的);
      $阿贾克斯({
      数据类型:JSON,
      网址:rate.php,
      数据:{storyidr:storyidr,值:值},
      键入:POST,
      成功:功能(数据){
          $('#响应+ storyidr).replaceWith(平均评级+ data.avg +'/ 10');
          $('#响应2+ storyidr).replaceWith('额定'+ data.cnt +'时代');

      },
           错误:函数(jxhr,味精,ERR){
           $('#响应)追加。('<李风格=颜色:红色>+味精+'< /李>');
      }
  });
   });
    < / SCRIPT>
 

PHP

 < PHP
            $ storyidr = $ _ POST ['storyidr'];
        $ mysqli的= mysqli_connect($ DBHOST,$数据库用户名,$ dbpasswd,$数据库名称)或死亡(无法连接到服务器。);
         如果(mysqli_connect_errno($ mysqli的))
           {
           回声无法连接到MySQL:。 mysqli_connect_error();
           }
        $ SQL =INSERT INTO评级(storyidr,等级,ENTRY_DATE)VALUES('$ _ POST [storyidr]','$ _ POST [值]',现在());;
        $ SQL =SELECT AVG(排名)AS avrank,COUNT(职级)AS countrank从收视率WHERE storyidr = $ storyidr。
        如果($ mysqli-> multi_query($ SQL))
        {$ mysqli-> next_result();
        如果($结果= $ mysqli-> store_result())
        {
        $数据= mysqli_fetch_assoc($结果);
        $ avrank = $数据['avrank'];
        $ countrank = $数据['countrank'];
        $ avrankr =圆($ avrank,2);
        如果(is_null($ avrank)){$ avrank =空;}
                  回声json_en code(阵列('平均'=> $ avrankr,'CNT'=> $ countrank));

        }
        }
    ?>
 

解决方案 Json和Ajax的简单理解

您应该只使用 json_en code()一次,并且只能随声附和该函数的结果。不止一次做无效的JSON:

 其他
    {
       $结果=阵列();
       $结果['AV'] = $ avrankr;
       $结果['CNT'] = $ countrank;

       回声json_en code($结果);
    }
 

然后,在你的JavaScript,您可以访问 data.av data.cnt 直接:

  $('#响应+ storyidr).replaceWith(平均评级+ data.av +'/ 10');
$('#响应2+ storyidr).replaceWith(data.cnt);
 

您也可以设置在Ajax调用的的dataType 参数所提到的@barell,但通常jQuery将找出答案正确了。

编辑::要避免你得到未定义错误,你应该做的是这样的:

  $结果=阵列(状态=>「不及格」);
...
如果 () {
    ...

      如果($结果)
      {
        $结果['状态'] ='成功';
        $结果['AV'] = $ avrankr;
        $结果['CNT'] = $ countrank;
      }
}

回声json_en code($结果);
 

现在,你可以检查 data.status 先在你的AJAX调用的成功回调,并采取相应的操作:

 成功:功能(数据){
   如果(data.status ==='失败'){
      //显示警告消息某处,这仅仅是一个例子
      警报(找不到任何结果!);
   } 其他 {
      $('#响应+ storyidr).replaceWith(平均评级+ data.av +'/ 10');
      $('#响应2+ storyidr).replaceWith('额定'+ data.cnt +'时代');
   }
},
 

I'm using a star ratings system to display rating data from SQL. Each item that can be rated has unique identifyer variable $id and each rating in ratings tabl has unique identifyer $storyidr. I would like this script to display:

the average rating the number of times the item has been rated.

The values are retirevable but they display on the page together and I can't see how to seperate them. FOr example, for an item that has an average rating of 4 and has been rated 200 times. when user clicks the data returns via AJAX looking like:

For 'response1' 4"200" For 'response2' 4"200"

I would like to be able to seperate them to look like:

For 'response1' 4 For '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));

        }
        }
    ?>

解决方案

You should only use json_encode() once and only echo the result of that function. Doing it more than once invalidates your json:

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

       echo json_encode($results);
    }

Then, in your javascript, you can access data.av and data.cnt directly:

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

You could also set the dataType parameter in your ajax call as mentioned by @barell, but normally jQuery will figure that out correctly already.

Edit: To avoid the undefined errors you are getting you should do something like:

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

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

echo json_encode($results);

Now you can check for data.status first in the success callback of your ajax call and take the appropriate action:

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'); 
   }
},