버튼을 누르면 비동기로 텍스트 변환

버튼을 누르면 비동기로 텍스트 변환

QA

버튼을 누르면 비동기로 텍스트 변환

본문

테스트로 간단하게 만들어 보았는데

버튼을 누르면 텍스트가 변환되야 합니다.


<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">First</th>      
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td class='tg'><span>Mark</span></td>      
      <td>
        <button>버튼</button>
      </td>
    </tr>
  </tbody>
</table>

 


<?php 
echo '텍스트 변경';

 


$(function(){
    $('body').on('click', 'button', function(){
        $.post({
            url: g5_url+'/ajax.test.php',
            data : {}
        }).done(function(result){            
            console.log(result);
            $(this).closest().closest().find('.tg').find('span').text(result);
        });
    });
});

 

제이쿼리 부분에서 위에 처럼 작성하면 안되는 건가요?

이 질문에 댓글 쓰기 :

답변 2


<body>
<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">First</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td class='tg'><span>Mark</span></td>
      <td>
        <button>버튼</button>
      </td>
    </tr>
  </tbody>
</table>
</body>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
var g5_url = 'http://domain.com';
$(function(){
    $('body').on('click', 'button', function(){
        var btn = $(this);
        //$.post({
        $.ajax({
            url: g5_url+'/ajax.test.php',
            type: 'POST',
            data : {}
        }).done(function(result){
            console.log(result);
            //$(this).closest().closest().find('.tg').find('span').text(result);
            btn.closest('tr').find('.tg').find('span').text(result);
        });
    });
});
</script>

 

$.post : https://api.jquery.com/jQuery.post/

$.ajax : https://api.jquery.com/jQuery.ajax/

일단 post 메소드부분을 잘못하셨네요. closest()는 부모를 타고 올라가서 찾는 메소드라 두번 쓸수없는 함수고, 셀렉터를 넣으셔야 합니다. parent()함수랑 헷갈리신듯 

ajax.test.php에서 리턴받을건 table.table에서 span을 찾아서 텍스트를 바꾸는 코드로 생각하고 짜봤습니다.



$(function(){
    $('body').on('click', 'button', function(){
        var $this = $(this);
        $.post(g5_url+'/ajax.test.php',function (result){
            console.log(result);
            $this.closest('.table').find('.tg span').text(result);
        },'html')
    });
});

답변을 작성하시기 전에 로그인 해주세요.
전체 402
QA 내용 검색
filter #ajax ×

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT