[英]Loading HTML dynamically using JavaScript and PHP
I have the following code:我有以下代码:
<?php
if ($x == 1){
?>
<b>Some html...</b>
<?php
}
else if ($x==2){ ?>
<b> Other html...</b>
<?php
}
?>
Now I would like to have two links below ( a href
) and somehow pass the variable $x
(so Link1 passes x=1
and Link2 passes x=2
) in order to load the relevant bit of code from if statement.现在我想在下面有两个链接(
a href
)并以某种方式传递变量$x
(所以 Link1 传递x=1
并且 Link2 传递x=2
)以便从 if 语句加载相关的代码位。 I know I can pass $x
using the form and then test its value and load required a bit of code, but I would like to do it smoothly, without reloading the page.我知道我可以使用表单传递
$x
,然后测试它的值并加载需要一些代码,但我想顺利完成,而无需重新加载页面。 I think that jQuery could help it, but I have no idea how to do it.我认为 jQuery 可以帮助它,但我不知道该怎么做。 Any ideas greatly appreciated.
任何想法都非常感谢。
Forgetting about PHP for the moment, you're looking for jQuery's .load()
:暂时忘记 PHP,您正在寻找 jQuery 的
.load()
:
<div id="container"></div>
<a href="javascript:void(0);" onclick="loadContent(1);">Load 1</a>
<a href="javascript:void(0);" onclick="loadContent(2);">Load 2</a>
<script type="text/javascript">
loadContent = function(content){
$('#container').load(content + '.html');
}
</script>
The above code (not tested, but it's at least close) will insert the contents of 1.html
, or 2.html
(on the server) into the div with id="container"
.上面的代码(未测试,但至少接近)将
1.html
或2.html
(在服务器上)的内容插入到id="container"
的 div 中。
There are plenty of tutorials, like the one linked in pygorex1' answer, that cover various ways of doing this.有很多教程,例如 pygorex1' 答案中链接的教程,涵盖了执行此操作的各种方法。
What you're looking for is AJAX - the ability to load server content using background HTTP requests in Javascript.您正在寻找的是AJAX - 在 Javascript 中使用后台 HTTP 请求加载服务器内容的能力。 Here's a tutorial I've found useful for implementing AJAX using JQuery:
这是我发现对使用 JQuery 实现 AJAX 很有用的教程:
http://articles.sitepoint.com/article/ajax-jquery http://articles.sitepoint.com/article/ajax-jquery
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.