Using smarty variable within a jQuery Function
My php generates some type from the DB and it is passed to a Smarty Variable $X.
With the help of Jquery, I want to be able to click a butt开发者_JS百科on, and the content of one of my div will be be replace with $X.
$(document).ready(function(){
$("button").click(function(){
$("#div1").html($X);
});
});
This piece of Jquery script is included in an external js file.
If you have a template file that is parsed where you can output PHP->Smarty assigned variables, something you could do is create a global JS variable in the template, and then use that global variable within your JS as normal.
Such as:
Template file
<script type="text/javascript">
var MyGlobalVar = "{$MyGlobalVar}";
</script>
Global.js file
$(document).ready(function(){
$("button").click(function(){
if (MyGlobalVar != '') {
$("#div1").html(MyGlobalVar);
} else {
alert('Error! Error! Abort!');
}
});
});
Note, you could output the Global.js file with it being parsed by Smarty (although... this is probably not a great idea) and inject your PHP->Smarty variables this way. This would treat the Global.js included file as a Smarty template.
To do so, you would need to use {literal}
, probably name the file with a .php file ending (so it was PHP-parseable), and add a PHP header()
call so PHP outputs the file contents to the browser as a Javascript content-type.
Global.js
<?php
header("content-type: text/javascript");
?>
var MyGlobalVar = "{$MyGlobalVar}";
{literal}
$(document).ready(function(){
$("button").click(function(){
if (MyGlobalVar != '') {
$("#div1").html(MyGlobalVar);
} else {
alert('Error! Error! Abort!');
}
});
});
{/literal}
Additionally, on the PHP side, you might want to consider adding slashes to your variable, especially if the JS variable will contain html or other bits of text that will use single/double quotes.
精彩评论