使用ajax,php和jQuery更改DIV内容

2022-08-30 16:52:57

我有一个div,其中包含数据库的一些文本:

<div id="summary">Here is summary of movie</div>

和链接列表:

<a href="?id=1" class="movie">Name of movie</a>
<a href="?id=2" class="movie">Name of movie</a>
..

该过程应如下所示:

  1. 点击链接
  2. Ajax使用链接的URL通过GET将数据传递到php文件/同一页面
  3. PHP 返回字符串
  4. div 将更改为此字符串

答案 1
<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",
     url: 'Your URL',
     data: "id=" + id, // appears as $_GET['id'] @ your backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

并在列表中添加事件onclick

<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>

答案 2

通过注册定位点的单击事件(使用 class=“movie”),并使用 .load() 方法发送 AJAX 请求并替换摘要 div 的内容,您可以使用 jQuery 轻松实现此目的:

$(function() {
    $('.movie').click(function() {
        $('#summary').load(this.href);

        // it's important to return false from the click
        // handler in order to cancel the default action
        // of the link which is to redirect to the url and
        // execute the AJAX request
        return false;
    });
});