채택완료

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

2022-09-02 (금) 15:17:50 1,974

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

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

Copy
<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>
Copy
<?php 
echo '텍스트 변경';
Copy
$(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개

채택된 답변
+20 포인트
Copy
<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을 찾아서 텍스트를 바꾸는 코드로 생각하고 짜봤습니다.

Copy
$(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')
    });
});

답변을 작성하려면 로그인이 필요합니다.