[英]Passing a variable from php to javascript on button click
Hi I am trying to pass a variable on button click from a php function to javascript. The output is undefined for some reason but at the php function the variable does contain data.您好我正在尝试将按钮单击时的变量从 php function 传递到 javascript。output 由于某种原因未定义,但在 php function 变量确实包含数据。 Any idea why this is happening?
知道为什么会这样吗?
PHP: PHP:
add_filter( 'page_row_actions', 'create_pdf_row_actions', 10, 2 );
function create_pdf_row_actions( $actions, WP_Post $post ) {
if ( $post->post_type != 'item' ) {
return $actions;
}
# $actions['create-pdf'] = "<a href='#?id=".$post->ID."' >Create PDF</a>";
$actions['create-pdf'] = "<a href='#?id=".$post->ID."' >Create PDF".$post->ID."</a>";
return $actions;
}
Javascript: Javascript:
jQuery(document).ready(function($){
$('.create-pdf').on('click', function () {
alert("button"+ $(this).data("id"));
});
});
Assuming from the piece of code, You can try:从这段代码假设,你可以尝试:
Calling the PHP function within jQuery by using the <?php?>
tags.使用
<?php?>
标签在 jQuery 内调用 PHP function。 Since $actions['create-pdf']
is inside an array, use print_r
to output the variable, or use foreach loop
if you have multipile key-value pairs由于
$actions['create-pdf']
在数组中,使用print_r
到 output 变量,或者如果你有多个键值对,则使用foreach loop
jQuery's .data()
accesses an element's dataset
but the id
in your link appears to be in the URL fragment of the href
attribute. jQuery 的
.data()
访问元素的dataset
,但链接中的id
似乎位于href
属性的 URL 片段中。
You have two options...你有两个选择...
Add the appropriate data-id
attribute to your link将适当的
data-id
属性添加到您的链接
$actions['create-pdf'] = sprintf( '<a href="#?id=%1$s" data-id="%1$s">Create PDF%1$s</a>', htmlspecialchars($post->ID) );
$(".create-pdf").on("click", "a[data-id]", function(e) { e.preventDefault(); alert(`button${$(this).data("id")}`); });
Or, extract the id
from the params in the URL fragment或者,从 URL 片段中的参数中提取
id
$(".create-pdf").on("click", "a[href]", function(e) { e.preventDefault(); const url = new URL(this.href); const params = new URLSearchParams(url.hash.slice(1)); alert(`button${params.get("id")}`); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.