我有一个使用开源PHP简单HTML DOM解析器的最小PHP脚本。当调用外部脚本时,读取网页并将其内容返回给显示它的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 在这里有售
我可以预见可能需要一个jQuery
解决方案来将php到-javascript内容转换为DOM元素。现在,我真正感兴趣的是让php
和javascript
互相交谈。
发布于 2014-12-30 12:40:20
您可以使用jQuery将AJAX请求中的url发布到PHP文件中。然后,PHP文件的内容将被发送回脚本,并作为参数传递给AJAX处理程序回调,命名为这里的数据。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>
https://stackoverflow.com/questions/27711023
复制