Grab images from URL and display them
I have a question about document object model in javascript.
I'm attempting to build a program that grabs images from a url and outputs them, I have actually done this in php using the code below but my question is how would I perform the same function in javascript?<?php
$url = 'http://lockerz.com/s/104049300';
$doc = new DOMDocument();
@$doc-&开发者_C百科gt;loadHTMLFile($url);
// Get all images
$images_list = $doc->getElementsByTagName('img');
foreach($images_list as $image) {
echo $image;
}
?>
You can't send a request to http://lockerz.com/ using ajax (assuming it's not your own domain), so you will need some server side script anyways. You might as well just use what you've got working in php, but change it to take the url as a parameter and return a JSON array like:
<?php
$url = $_GET['url'];
// sanitize url here, possible verify that it begins with http://lockerz.com, or something
$doc = new DOMDocument();
@$doc->loadHTMLFile($url);
// Get all images
$images_list = $doc->getElementsByTagName('img');
$out = '[';
foreach($images_list as $image) {
$out .= $image.',';
}
echo substr($out, 0, -1).']';
?>
Then use javascript to send ajax requests to your own php page and do what you want with the array returned.
Pure client side solution based on AJAX or iframe will violate the same origin policy. That is once using AJAX (or iframe) to get pages not on your web site, browser will ban this behavior.
I suggest using server side to fetch the page and pass it back to client.
Server side: http://your-host/fetch.php
<?php
$url = $_GET['url'];
echo file_get_contents($url);
?>
Client side (based on jQuery):
<script>
$.get('http://your-host/fetch.php', {url: 'http://lockerz.com/s/104049300'}, function(data) {
var imgs = $('<div/>').html(data).find('img');
imgs.each(function(i, img) {
alert(img.src); // show a dialog containing the url of image
});
});
</script>
You can get the content of a website using jQuerys .load() method. After you got the html you can parse the html source.
http://api.jquery.com/load/
hope that helps
精彩评论