Jquery ajax仅在第一次运行

时间:2016-12-28 04:11:54

标签: javascript jquery html ajax

我在jquery中使用ajax post来构建页面的一部分。但问题是它只运行一次。这是我的代码

<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 个答案:

答案 0 :(得分:1)

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

&#13;
&#13;
$(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);
      }
    });
  });
});
&#13;
<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>
&#13;
&#13;
&#13;