javascript - 通过单击复选框启动 smarty 函数

标签 javascript jquery json smarty

我正在玩弄 smarty 和 jquery...

实际上我有一个更大的项目,我想改进我的源代码以便更好地处理。

现在我拥有的是一个包含一些内容的 HTML 页面 (.tpl)。在一行中,我有一个复选框,例如:

<input type="checkbox" aria-label="..." checked>
<button onclick='fnTest({$options})'>test</button>

因为我想调用一个 js 函数并通过 JSON 传递一些数据,所以我在这个页面中有一行看起来像:

{$options = '{"preview":1, "extra_paper":0}'}

实际上只是简单地创建了一个包含 JSON 字符串的 Smarty 变量。

在我的 jsFile 上只是简单地使用 console.log()(目前)来查看传递了什么。

function fnTest(obj){
    console.log(obj);
}

一切都很好,直到这里。现在我想在选中/取消选中复选框后立即更改 JSON 字符串中的一些内容。

检查:

{$options = '{"preview":1, "extra_paper":1}'}

未勾选

{$options = '{"preview":1, "extra_paper":0}'}

我尝试使用 Smarty 函数

{function name=presets}
    //some source to write the JSON-String new
    {$data}
{/function}

那叫像

{presets data="checkstatus"}

但这里的问题是,我不知道如何在复选框操作上启动此功能...

有没有其他方法可以做到我想做的...

所以主要的问题是:

是否有可能在复选框事件上启动 Smarty 函数?

有没有办法在模板上重新创建 JSON 字符串并将其传递给函数?

最佳答案

您的 javascript 代码不知道 HTML 是如何生成的,无论是从 PHP/Smarty 还是任何其他方式。

您可以做的是对您的服务器进行 AJAX 调用以获取新生成的 HTML,并将其注入(inject)到您想要的任何位置:

$('.yourCheckbox').change(function(event){

  // you get 'someParam' from either your checkbox status, or from the surrounding form...it's up to you
  $.get('path/to/your/script', { someParam : someValue }, function(data){

    // inject received html into a proper div
    $('someSelector').html(data);

  });

});

然后您需要了解以下内容:

  • 不编写内联 js [例如onclick=...;
  • 使用正确的路由系统,而不是普通的 path/to/myScript.php

关于javascript - 通过单击复选框启动 smarty 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27798114/

相关文章:

jquery - 数据表警告(表 ID = 'table-filter'): Requested unknown parameter '0' from the data source for row 0 error in data tables

Javascript OnFocus 和 OnBlur 事件

iphone - 如何将 JSON 序列化数据转换为 NSDictionary

java - JSON 解析为 ArrayList。如何让它在 onPostExecute 中重复多个 map 标记的数据?

javascript - 如何让我的文本在 Unity 中显示我的分数?

javascript - 如何从匿名函数正确调用外部类方法

javascript 添加新表单

javascript - AJAX + jQuery 困惑?

javascript - React Promise 代码需要更改 json 值

javascript - 有什么方法可以将具有相同 css 值的多个 textContent 放入 JavaScript 中的变量中?