Embed Php code in ajax success method
I'm using 开发者_JAVA技巧jquery ajax can i use php code in success: function(html){}
??
No, jquery/JavaScript code is executed at the client side. You can either write JavaScript/jQuery code or preprocess the answer to the XHR request in php.
No, not directly, as JavaScript ist executed on the client side, and PHP is executed on the server.
A workaround would be to send another AJAX-Request from your success-function. But it can only do things on the server side, not on the client side.
If you just want to download a file from your callback function, use location.href = url
. The URL can be a server side PHP script serving the data stream, or a real file.
Yes.
For instance, you could do:
success: function(html) {
<?php echo 'alert("Hello, World!");' ?>
}
Since JS is all client side and PHP is server side, the two cannot be executed within each other synchronously. However, you can use AJAX to ask PHP to execute code on values, but if you already have an AJAX query to PHP going, why not just do it then.
You use PHP indirectly anyhow. There is no need to note in the success function:
$.ajax({
url: "execute.php",
success: function(html){}
And the html
comes directly from the execute.php
script. And this is where you do any PHP stuff like:
<?php echo "<div>" . php_stuff() . "</div>"; ?>
Think of the PHP script as the first half of the execution, and the jQuery success: callback as the second part of the AJAX call.
精彩评论