我有一个最小的 PHP 脚本,它利用开源 PHP Simple HTML DOM Parser 。调用外部脚本时,会读取网页并将其内容返回到显示它的 index.php
。我在下面展示的基本示例可以工作,但我想将 PHP 调用集成到 JavaScript 中以使其具有交互性。
index.php
<html>
<head>
<title>php / javascript interaction</title>
</head>
<body>
<?php include 'simple_html_dom_utility.php';?>
<?php include 'webpage_parser.php';?>
<script type="text/javascript">
// this Javascript isn't fully implemented but illustrates the intent..
links = ["http://en.m.wikipedia.org/wiki/Moon", "http://en.m.wikipedia.org/wiki/Star",
"http://en.m.wikipedia.org/wiki/Planet", "http://en.m.wikipedia.org/wiki/Sun"];
k = 0;
window.setInterval(function(){ // rotate through webpages
var newurl = links[ k ];
console.log(newurl);
// call PHP here with 'newurl' argument to append new website's content to the DOM
k = (k+1) % links.length;
}, 5000);
</script>
</body>
</html>
webpage_parser.php
<?php
// this needs to change to accept input arguments for $url
$url = "http://en.m.wikipedia.org/wiki/Sun";
$html = file_get_html($url);
echo $html;
?>
simple_html_dom_utility.php is available here
我可以预见可能需要一个 jQuery
解决方案来将 php 到 javascript 内容转换为 DOM 元素。现在我真的只是对让 php
和 javascript
相互交谈感兴趣。
最佳答案
您可以使用 jQuery 将 AJAX 请求中的 URL 发布到 PHP 文件。然后,PHP 文件的内容将被发送回脚本,并作为参数传递到 AJAX 处理程序回调中,此处名为 data。 jQuery 还可以使用 $('element').html(data);
webpage_parser.php
<?php
require 'simple_html_dom_utility.php';
if(!$_POST['url']) {
$url = "http://en.m.wikipedia.org/wiki/Sun";
}
else {
$url = $_POST['url'];
}
$html = file_get_html($url);
?>
<div>
<?php echo $html; ?>
</div>
这个显示内容的页面并不需要是 PHP 的。 index.html
<html>
<head>
<title> Ajax example </title>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
links = ["http://en.m.wikipedia.org/wiki/Moon", "http://en.m.wikipedia.org/wiki/Star",
"http://en.m.wikipedia.org/wiki/Planet", "http://en.m.wikipedia.org/wiki/Sun"];
var k = 0;
setInterval(function(){
$.post("webpage_parser.php", { url: links[k] }, function(data,status){
if(!data) {
console.log(status)
}
else {
$('#content').html(data);
}
});
if(k < links.length) {
k++;
}
else {
k = 0;
}
}, 5000);
</script>
</head>
<body>
<div id="content">
</div>
</body>
</html>
关于javascript - Javascript 和 PHP 之间的简单交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27711023/