如何从AJAX查询中检索和使用数据

时间:2017-10-20 13:45:23

标签: jquery ajax

我有一个Ajax查询:

$(document).ready(function(){   
  $("#amis_commun_liste .afficher_plus_modal").bind('click',function f(){
    var afficher_plus_modal = $(this).attr("class");
    var id = "<?php  echo $_GET['id']; ?>";

    $(this).unbind('click',f);
    $.ajax({
      type: "post",
      url: "voir_profil_includes/func_infos.php",
      data: {
        "afficher_plus_modal": afficher_plus_modal,
        "id" : id           
      },
      beforeSend: function() {
        $("#amis_commun_liste .afficher_plus_modal").html("En cours");
      },
      success: function(data) {
        if (data =="success") {                          
          //Treatment area after successful operation
        }
      }
    });
  });
});

Ajax查询将此php / mysql查询调用到func-infos.php:

if (!empty($_POST['afficher_plus_modal'])) {
   require("../voir_profil_includes/connect_db.php");
    $infos = [];
    $q = $bdd->prepare(" SELECT u.id,
  u.nom, u.prenom, u.avatar,u.couverture
FROM users u
INNER JOIN
(
  SELECT id_exp, id_des
  FROM friends
  WHERE id_exp IN(:id_exp, :id_des)
    AND active = 1
  UNION
  SELECT id_des, id_exp
  FROM friends
  WHERE id_des IN(:id_exp, :id_des)
    AND active = 1
) tmp ON tmp.id_des = u.id
GROUP BY u.id
HAVING COUNT(*) = 2
ORDER BY RAND() LIMIT 5
");
     $q->execute(array(
                    "id_exp" => $_POST["id"],
                    "id_des" => info_profil()->id
                    ));
      while ($info = $q->fetch(PDO::FETCH_OBJ)) {
             $infos[] = $info;               
             }      
     // return data after operation
        return $infos;
     //informs Ajax that the operation has been carried out
     echo "success";
}

此代码不会产生错误,但我不知道如何检索从func_infos.php返回的数据以更新&#34; list_am_commun.php&#34;页面通过在list_am_commun.php中显示新数据。
谢谢,但我知道这不是一件简单的工作。

1 个答案:

答案 0 :(得分:1)

dataType添加到ajax来电,如下所示:

$.ajax({
  dataType: "json",
  type: "post",

然后将您的php更改为如下所示:

echo json_encode($info) ;

没有echo 'success';

ajax返回时,data将作为object返回,您可以通过

访问它

data.{objectName}

  

更新

您的javascript应如下所示:

$(document).ready(function(){   
$("#amis_commun_liste .afficher_plus_modal").bind('click',function f(){
    var afficher_plus_modal = $(this).attr("class");
    var id = "<?php  echo $_GET['id']; ?>";

    $(this).unbind('click',f);
    $.ajax({
      type: "post",
      dataType: "json", //I added this line, to force the returned data to be formatted as json
      url: "voir_profil_includes/func_infos.php",
      data: {
        "afficher_plus_modal": afficher_plus_modal,
        "id" : id           
      },
      beforeSend: function() {
        $("#amis_commun_liste .afficher_plus_modal").html("En cours");
      },
      success: function(data) {
        console.log(data) ; //Console the returned data, and you can then treat is as you wish.
      }
    });
  });
});

在你的php中:

删除echo "success";并将其替换为echo json_encode($infos);

这必须解决您的问题