【问题标题】:Get a user input instead of hardcoding an input into array获取用户输入而不是将输入硬编码到数组中
【发布时间】:2016-12-18 01:18:27
【问题描述】:

我正在尝试让用户输入到 Wordpress 查询数组中。我可以使用我的 jquery 代码获取输入,但我想将其添加到 php 数组中的 'meta_value' => '123456', 中。如何将 jquery 脚本中的'meta_value' => '123456', 从 '123456' 更改为 var x?

如果这不可能,有人可以建议另一种从输入字段中获取'meta_value' => '123456', 的方法吗?

<script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery("#bt").click(function(){
            var x = jQuery("#txt_name").val();
            alert(x);
        });
    });

</script>

<input type="text" id="txt_name"  />
<input type="button" id="bt"  value="click here" />




<?php

 $args = array(
        'meta_key' => 'cardnum',
        'meta_value' => '123456',
        'meta_compare' => '='
    );

$user_query = new WP_User_Query( $args );

// User Loop
if ( ! empty( $user_query->results ) ) {
    foreach ( $user_query->results as $user ) {
        echo '<p>' . $user->cardnum ." ". $user->nickname . '</p>';
    }
} else {
    echo 'Not available number.';
}
?>

【问题讨论】:

  • 您需要使用 ajax 或表单将该数据发送到服务器。 PHP 不在浏览器中运行。网上有很多关于使用 ajax 以及 ajax 和 wordpress 的教程
  • 感谢您的帮助。

标签: javascript php jquery arrays wordpress


【解决方案1】:

您不需要使用表单或 Ajax - 您可以使用 URL 查询字符串。

当 jquery 函数触发时,重新加载页面 URL,但这次包括一个包含变量的查询字符串。

然后你可以通过PHP提取变量。

(这是启用服务器端处理源自客户端的变量的最快和最简单的方法。)

HTML:

<input type="text" id="txt_name"  />
<input type="button" id="bt"  value="click here" />

jQuery:

$(document).ready(function(){
    $("#bt").click(function(){
        var x = $("#txt_name").val();
        window.location.href += '?x=' + x;
    });
});

PHP:

<?php
parse_str($_SERVER["QUERY_STRING"]);
echo '<p>The value of <strong>x</strong> is... '.$x.'</p>'; 
?>

【讨论】:

  • 这是描述 GET ......所以答案是冲突的,也不是很完整
猜你喜欢
  • 2014-07-07
  • 2015-03-23
  • 2021-11-18
  • 2013-01-16
  • 2022-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多