在javascript中解析JSON响应会在追加时返回重复的行

时间:2017-08-30 16:18:10

标签: javascript json ajax symfony

我刚刚从控制器返回一个响应,我正在使用symfony3并将其解析为一个html表,但结果是我的代码下面的重复行:

控制器:

            $em = $this->getDoctrine()->getManager();

            $RAW_QUERY = 'SELECT id,DO_Date,DL_Design,DL_Qte,DL_MontantHT,DL_MontantTTC FROM `facture_ligne` WHERE facture_id=:id';

            $statement = $em->getConnection()->prepare($RAW_QUERY);
            // Set parameters
            $statement->bindValue('id', $id);
            $statement->execute();

            $facture = $statement->fetchAll();

            $serializer = $this->container->get('jms_serializer');
            $reports = $serializer->serialize($facture,'json');
            return new Response($reports);

我的剧本:

{% for fact in facture %}

                                    <script>

                                        ( function () {


      var z= new XMLHttpRequest();
      z.open("get","{{ path('Ajaxonify',{'id':fact.id}) }})",true);

                                            z.send()

z.onreadystatechange = function result () {
          var obj=z.responseText;
          if(obj!="")
          {
              json = JSON.parse(obj);

              var tr;
              for (var i = 0; i < json.length; i++) {
                  tr = $('<tr/>');
                  tr.append("<td>" + json[i].id + "</td>");
                  tr.append("<td>" + json[i].DO_Date + "</td>");
                  tr.append("<td>" + json[i].DL_Design + "</td>");
                  tr.append("<td>" + json[i].DL_Qte + "</td>");
                  tr.append("<td>" + json[i].DL_MontantHT + "</td>");
                  tr.append("<td>" + json[i].DL_MontantTTC + "</td>");

                  $('#tb{{ fact.id  }}').append(tr);
              }
          }
      }
})();

这就是结果: enter image description here

1 个答案:

答案 0 :(得分:1)

尝试添加XMLHttpRequest.readyState

的检查
z.onreadystatechange = function result () {
    if (z.readyState != 4) {
        return;
    }
    .... 
}