hx-vals
hx-vals
属性允许你添加到将随 AJAX 请求提交的参数。
¥The hx-vals
attribute allows you to add to the parameters that will be submitted with an AJAX request.
默认情况下,此属性的值是 JSON(JavaScript 对象表示法) 格式的名称表达式值列表。
¥By default, the value of this attribute is a list of name-expression values in JSON (JavaScript Object Notation) format.
如果你希望 hx-vals
评估给定的值,则可以在值前加上 javascript:
或 js:
。
¥If you wish for hx-vals
to evaluate the values given, you can prefix the values with javascript:
or js:
.
<div hx-get="/example" hx-vals='{"myVal": "My Value"}'>Get Some HTML, Including A Value in the Request</div>
<div hx-get="/example" hx-vals='js:{myVal: calculateValue()}'>Get Some HTML, Including a Dynamic Value from Javascript in the Request</div>
使用评估代码时,你可以访问 event
对象。此示例包括输入中最后输入的键的值。
¥When using evaluated code you can access the event
object. This example includes the value of the last typed key within the input.
<div hx-get="/example" hx-trigger="keyup" hx-vals='js:{lastKey: event.key}'>
<input type="text" />
</div>
你还可以使用扩展运算符动态指定值。这允许你包含函数返回的对象的所有属性:
¥You can also use the spread operator to dynamically specify values. This allows you to include all properties from an object returned by a function:
<div hx-get="/example" hx-vals='js:{...foo()}'>Get Some HTML, Including All Values from foo() in the Request</div>
在此示例中,如果 foo()
返回像 {name: "John", age: 30}
这样的对象,则 name
和 age
都将作为参数包含在请求中。
¥In this example, if foo()
returns an object like {name: "John", age: 30}
, both name
and age
will be included as parameters in the request.
¥Security Considerations
默认情况下,hx-vals
的值必须是有效的 JSON。它不是动态计算的。如果你使用 javascript:
前缀,请注意你正在引入安全注意事项,特别是在处理用户输入(例如查询字符串或用户生成的内容)时,这可能会引入 跨站点脚本 (XSS) 漏洞。
¥By default, the value of hx-vals
must be valid JSON.
It is not dynamically computed. If you use the javascript:
prefix, be aware that you are introducing
security considerations, especially when dealing with user input such as query strings or user-generated content,
which could introduce a Cross-Site Scripting (XSS) vulnerability.
¥Notes
hx-vals
是继承的,可以放在父元素上。
¥hx-vals
is inherited and can be placed on a parent element.
变量的子声明覆盖父声明。
¥A child declaration of a variable overrides a parent declaration.
具有相同名称的输入值将被变量声明覆盖。
¥Input values with the same name will be overridden by variable declarations.