Calling some jQuery on page load
I have an ajax load function that uses jQuery when an <a><a/>
is clicked further up the page.
This also triggers a cookie to be planted, so that the opened document remains if the user comes back.
<a id="request" onClick="createCookie('foobar')">Click me</a>
<div id="result" class="functions">
</div>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img class='loading' src='loading.gif' alt='loading...' />";
var loadUrl<?=$request->id?> = "viewrequest.php?id=<?=$request->id?>";
$("#display").click(function(){
$("#result").html(ajax_load).load(loadUrl)开发者_C百科;
var loaded<?=$request->id?> = 1
});
</script>
</div>
That works fine. What I want to do is use php to see if the cookie exists (easy).
if(isset($_COOKIE['foobar']))
and then, trigger the AJAX.
That's the bit I can't work out how to do. I assume the id="request" in the < a > triggers the AJAX when clicked, but I can't think how to do it on load inside the php if loop.
This should do the trick (untested, but the logic is good)
<?php if(isset($_COOKIE['foobar'])): ?>
<script type="text/javascript">
$(document).ready(function(){
var ajax_load = "<img class='loading' src='loading.gif' alt='loading...' />";
var loadUrl<?=$request->id?> = "viewrequest.php?id=<?=$request->id?>";
$("#display").click(function(){
$("#result").html(ajax_load).load(loadUrl);
var loaded<?=$request->id?> = 1
});
});
</script>
<?php endif; ?>
use
$(window).load(function(){
//code
});
or
$(document).ready(function(){
//code
});
depending on when you actually need it to execute.
window.load will wait for the full DOM to be loaded.
document ready doesn't wait for all requests to complete
PHP can't directly trigger javascript. Remember that PHP executes on the server, while Javascript executes on the client.
At most, PHP can output a small snippet of javascript while the page is being built, and embed a function call into that snippet>
<?php
if (isset($_COOKIE['foobar'])) {
echo <<<EOL
<script type="text/javascript">
the_cookie_is_set();
</script>
EOL;
}
?>
which would then run your function when the page is loaded/processed by the client.
However, since you're using AJAX, that implies you've had Javascript send something to the server and get a response. Why not use the response handler to trigger that function?
精彩评论