I have a function which loads some content when executed...
IE...
function load_product(product_id) {
$.ajax({
type: 'GET',
url: 'product_开发者_运维百科image.php',
data: 'product_id='+product_id+'',
success: function(data) {
$('#product_image').html(data);
}
});
}
That works great. But say I want to create a link to a page, so that then something triggers to load up the dynamic content?
IE I link to a page, say
www.blah.com/?product=1
and a few 'divs' on the page that load up different things dynamically for product #1.
The way I currently do it is by doing something:
<?php
if($_REQUEST['product_id']) {
echo '
<script type="text/javascript">
$(document).ready(function(){
load_product(' . $_REQUEST['product_id'] . ');
});
</script>
';
}
And I put that somewhere on the new page being loaded. It works. But is there a better way?
I do something similar but using YepNope.js.
<script>
var hasProduct = <?php echo isset($_REQUEST['product']) ? 'true' : 'false' ?>
yepnope({
test : hasProduct,
yep : 'js_file_to_load.js',
});
</script>
Then you can store all you main js in an external file. This has the added advantage over your method in that, I don't have to load the external scripts for every request just in case $_REQUEST['product']
is set.
You can do this all in JavaScript. Use 'location.search' to give you the query part of the current URL... for example, if the url is "www.blah.com/?product=1" then location.search returns "?product=1". Then you can just use split('=') to get part number. Of course, you can also just get the whole URL using 'location.href'... doesn't really matter.
var productNum = parseInt(location.search.split('=')[1]);
You would probably want more checks in there, but that's the basic idea.
精彩评论