我有一个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/