简体   繁体   English

我该如何通过Smarty函数传递javascript变量?

[英]How can I pass a javascript variable through a function with Smarty?

I am trying to pass a parameter to a function with Smarty . 我正在尝试将参数传递给Smarty函数。 Like this: 像这样:

$('#buttonClose').click(function(){
    var name = document.getElementById('nameSpan').value;
    {$person->addName(name)}
});

but it pass the value "name" instead of the real value of the variable name . 但它传递的是值“ name”而不是变量name的实际值。

How can I do that to get the real value of the variable name in the function addName ? 我该怎么做才能在函数addName获取变量name的真实值?

Thanks in advance! 提前致谢!

All the Smarty code is run on the server, not the client. 所有Smarty代码都在服务器而不是客户端上运行。 If you have Smarty function calls in your Javascript, they will be run at the time the page is rendered - not when the function/event is called in the client's browser. 如果您的Javascript中有Smarty函数调用,它们将在呈现页面时运行-而不是在客户端浏览器中调用函数/事件时运行。 If you want to run a PHP call from Javascript, you must create a PHP endpoint such as addname.php and call it using an AJAX request. 如果要从Javascript运行PHP调用,则必须创建一个PHP终结点(例如addname.php并使用AJAX请求对其进行调用。

$('#buttonClose').click(function(){
    var name = document.getElementById('nameSpan').value;
    $.post( "addname.php", { name: name, person: person_id } );  
});

You can't assign a client-side value to a smarty variable, as smarty is a templating language that runs on the server. 您不能将客户端值分配给smarty变量,因为smarty是在服务器上运行的模板语言。 Smarty assignments can only be done on the server-side, that is to say, from PHP. Smarty分配只能在服务器端进行,也就是说,可以从PHP进行。 Eg: 例如:

$smarty->assign('timestamp',time());

So what you can do is something like: 因此,您可以执行以下操作:

$smarty->assign('timestamp',time()); //in your PHP script

//in your JS
var currentTS = {$timestamp};

See http://www.smarty.net/manual/en/api.assign.php 参见http://www.smarty.net/manual/en/api.assign.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM