2016-12-28 84 views
0

我使用AJAX后jQuery中,通过该页面的一部分是建立运行。但问题是它只运行一次。这里是我的代码如下jQuery的AJAX只是首次

<html> 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    <script> 
     var res; 
     function on(id){ 
     var dat = ''; 
     $.ajax({ 
      url: 'ajax.php', //This is the current doc 
      type: "GET", 
      data: {a: id }, 
      success: function(data){ 
      res = data; 
      data += '<div class="white" id="white" style="display:none">'; 
      var result = $.parseJSON(res); 
      $.each(result, function(k, v) { 
       //display the key and value pair 
       dat += "<a href = 'javascript:void(0);' onclick='on("+ k +")'>"+ v+"</a><br>"; 
      }); 
      document.write(dat); 
      } 
     }); 
     } 
    </script> 

    </head> 
    <body> 
    <a href="javascript:void(0);" onclick="on(8);">Get JSON data</a> 
    </body> 
</html> 

点击第一次后,页面显示结果后继续加载。而第二后单击它显示错误ReferenceError: on is not defined

实际上它应该发生在每次点击href id时都会在jquery函数中传递,并基于该sql查询运行返回数据并显示新的页面数据。每次在href上单击这个应该会发生。

+1

工作正常,我在这里https://plnkr.co/edit/tcbHOtSL69rN7hSk3SXY – Deep

回答

1

你真的应该重新考虑你的事件处理:

$(function() { 
 
    var res; 
 
    $(".getJson").click(function (e) { 
 
    e.preventDefault(); 
 
    var dat = ''; 
 
    var id = $(this).data(id); 
 
    $.ajax({ 
 
     url: 'ajax.php', //This is the current doc 
 
     type: "GET", 
 
     data: {a: id}, 
 
     success: function(data) { 
 
     res = data; 
 
     data += '<div class="white" id="white" style="display:none">'; 
 
     var result = $.parseJSON(res); 
 
     $.each(result, function(k, v) { 
 
      //display the key and value pair 
 
      dat += "<a href = 'javascript:void(0);' onclick='on(" + k + ")'>" + v + "</a><br>"; 
 
     }); 
 
     $("#output").append(dat); 
 
     } 
 
    }); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<a href="javascript:void(0);" data-id="8" class="getJson">Get JSON data</a> 
 
<span id="output"></span>

+0

还是同样的问题 – smarttechy

+0

什么的输出PHP文件。让我们来解决这个问题@smarttechy ... –

+0

你有一些问题,比如'dat',而不是'data' @smarttechy ... –