jquery - 使用ajax将链接id传递到php页面并在另一个div中打开

标签 jquery ajax jquery-ajaxq

我有一个index.php页面,其链接如下:

<a id="link" href="test.php?id=1">Test</a>

我在同一页面上有一个 div 容器,如下所示:

<div id="container" class="panel-body">

同一页面上的ajax jQuery代码如下:

<script type="text/javascript">
$("#link").click(function(){
    $.ajax({
    type: "get",
      url: "test.php",
      data: {'data':dataString}, 
      success: function(data){
           $('#container').html(data); 
      }
    });
}); 
</script>   

我的工作是将链接中的上述 id=1 传递给 test.php 并获取显示在同一页面的 div #container 中的值。

问题在于,单击链接会在新窗口中打开一个新页面,其中包含 url test.php?id=1,而不是在同一页面上显示 php 内容。

如何在 jquery 中同一页面的名为 #container 的 div 上显示 test.php 页面的结果???

提前致谢。

最佳答案

The issue is that clicking on link opens a new page in a new windows with url test.php?id=1 rather than displaying content of php on same page.

您需要使用 event.preventDefault() 停止 anchor 的默认行为:

$("#link").click(function(e) {
  e.preventDefault(); // <-------stop the def behavior here.
  var id = this.href.split('=').pop(); // extract the id here
  $.ajax({
    type: "get",
    url: "test.php",
    data: {id:id}, // now pass it here
    success: function(data) {
      $('#container').html(data); //copy and paste for your special case
    }
  });
});

关于jquery - 使用ajax将链接id传递到php页面并在另一个div中打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36262895/

相关文章:

javascript - 使用jquery在页面登录

javascript - 如何使用JQuery用Div包装数据动态数据

php - 无需重新加载页面即可更改的动态计数器

javascript - 即使操作成功,Ajax post 也返回 404

javascript - 使用 jQuery Ajax 将数据从 MySQL 加载到 JavaScript Array of Array

ajax - 如何在 Jquery Ajax 中向请求添加 header ?

javascript - 单独的 Div 中的多个 Google 可视化图表实例

javascript - 附加文件停止工作 octobercms 电子邮件 ajax 表单

javascript - 如果我已经有服务器端代码,如何发送 onClick JavaScript 电子邮件?

jquery - 如何设置 Ajax 调用的最短持续时间?