admin管理员组文章数量:1410705
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 button, 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.
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 button, 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.
Share Improve this question edited May 28, 2011 at 19:21 casperOne 74.6k19 gold badges189 silver badges260 bronze badges asked May 28, 2011 at 18:49 William ShamWilliam Sham 13.3k11 gold badges51 silver badges67 bronze badges1 Answer
Reset to default 4If 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.
本文标签: phpUsing smarty variable within a jQuery FunctionStack Overflow
版权声明:本文标题:php - Using smarty variable within a jQuery Function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744847299a2628286.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论