JQuery和Ajax:如何在变量中存储返回的数据?

时间:2016-10-19 17:48:42

标签: javascript php jquery ajax

我有以下代码:

  window.onload = function() {  
      var eMail = "<?php echo $log; ?>"; 
      var aRticleid = "<?php echo $articleid1; ?>"; 
      $.ajax({
              type: "GET",
              url: 'aquireLikes.php?email='+eMail+'&id='+aRticleid+'',
              success: function(data){
              }
          });
      };

执行php脚本。如果满足某些条件,PHP脚本中有三个变量设置为true。我想将这些变量的返回值存储在我的页面上的一组JavaScript变量中,这些变量调用aquireLikes.php页面。我怎样才能做到这一点?它会是这样的,但实际上是有效的:

  window.onload = function() {  
      var eMail = "<?php echo $log; ?>"; 
      var aRticleid = "<?php echo $articleid1; ?>"; 
      $.ajax({
              type: "GET",
              url: 'aquireLikes.php?email='+eMail+'&id='+aRticleid+'',
              success: function(data){

                var liked = aquirelikes.php.$liked;
              }
          });
      };

我知道上面是完全废话,但你得到了提示。那么如何将返回的值存储在javascript变量中呢?这是我的aquireLikes文件:

    <?php

    $email = $_GET["email"];
    $articleid1 = $_GET["id"];
    $done = false;

     $thing = mysql_query("SELECT `id` FROM likes WHERE id=(SELECT MAX(id) FROM likes)");
     $lastrow = mysql_fetch_row($thing);
     $lastid = $lastrow[0];

     if($lastid == null || $lastid == '0'){
       $lastid = '1';
     }   

     $state1 = '';

     for ($i=1; $i <= $lastid+1; $i++) { 
        $current = mysql_query("SELECT * FROM likes WHERE id=$i");
        while ($row = mysql_fetch_array($current)) {
           $id1 = $row[0];
           $userid1 = $row[1];
           $state1 = $row[2];
           $articleid1 = $row[3];
       if($done == false){
         if($email == $userid1 && $articleid1 == $id && $state1 == '1'){
          $liked = true;
          $disliked = false;
          $done = true;
          echo "<script>console.log('Liked!');</script>";
          break;
         }else{
          $liked = false;

         }
         if($email == $userid1 && $articleid1 == $id && $state1 == '0'){
          $disliked = false;
          $liked = false;
          $done = true;
          echo "<script>console.log('NONE!');</script>";

          break;
         }
         if($email == $userid1 && $articleid1 == $id && $state1 == '2'){
          $disliked = true;
          $liked = false;
          $done = true;
          echo "<script>console.log('disliked!');</script>";

          break;
         }else{
          $disliked = false;
         }
       }
      }


     }





?>

1 个答案:

答案 0 :(得分:0)

你的ajax看起来像这样:

    var liked;
    $.ajax({
          type: "GET",
          url: 'aquireLikes.php?email='+eMail+'&id='+aRticleid+'',
          type: 'json',
          success: function(data){

            liked = data.liked;
          }
  });

在php中你必须返回:

echo json_encode($data)

Php文件只能输出json数据!

这只是实施的一个例子。