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

Lui*_*uis 22 javascript php ajax jquery

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

<div id="summary">Here is summary of movie</div>
Run Code Online (Sandbox Code Playgroud)

和链接列表:

<a href="?id=1" class="movie">Name of movie</a>
<a href="?id=2" class="movie">Name of movie</a>
..
Run Code Online (Sandbox Code Playgroud)

这个过程应该是这样的:

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

ana*_*ria 54

<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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 7

通过注册锚点的click事件(使用class ="movie")并使用该方法发送AJAX请求并替换摘要div的内容,您可以使用jQuery轻松实现这一点.load():

$(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;
    });
});
Run Code Online (Sandbox Code Playgroud)