2016-12-28 1 views
0

jquery에서 ajax 게시물을 사용하여 페이지의 일부분을 구성했습니다. 그러나 문제는 그것이 단 한 번만 실행된다는 것입니다. 다음은 내 코드입니다.처음으로 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

'data' 대신에'dat'과 같은 몇 가지 문제가 있습니다. @smarttechy ... –

관련 문제