【问题标题】:How to use php to feed data to jQuery autocomplete?如何使用 php 将数据提供给 jQuery 自动完成功能?
【发布时间】:2010-12-01 17:26:54
【问题描述】:

这是earlier post 的延续。不幸的是,发布的解决方案不起作用,我的后续问题也没有得到解决。以防万一这是因为我慷慨的受访者没有注意到我已回复,我将重新发布我的问题。


我正在尝试构建一个表单,其中某些文本字段和文本区域具有自动完成功能。

我使用了强大的 wordpress 插件来构建我的表单。我将jQuery autocomplete plugin 用于自动完成部分。

在实施了我的一位受访者的建议后,代码现在如下所示:

<script> 
$(document).ready(function(){ 
<?php global $frm_entry_meta; 
$entries = $frm_entry_meta->get_entry_metas_for_field(37, $order=''); ?> 
var data = new Array(); <?php foreach($entries as $value){ ?>
data.push(unescape('<?php echo rawurlencode($value); ?>'); 
<?php } ?> 
$("#field_name-of-the-school").autocomplete(data); }) 
</script>

// 37 is the field id I want to pull from in the database, 
// and #field_name-of-the-school is the css id 
// for the text field in the form where a user can enter the name of a school. 
// the data for that field is stored in the db under field id 37. 
// other fields, like school id, have their own field ids.

我的受访者建议添加data.push(unescape('&lt;?php echo rawurlencode($value); ?&gt;'); 位。不幸的是,它仍然无法正常工作。

顺便说一句,代码在 page.php 的正文中,这是 wordpress 用来生成静态页面的模板(表单在其中之一上)。

我会认真、认真地感谢任何和所有的帮助。如果这种方法是死胡同(在早期的帖子中,还有另外两个答案让我头疼),我将非常愿意学习一些新技巧(尽管指向相关的学习资源确实会有所帮助.)

提前致谢。

【问题讨论】:

    标签: php jquery wordpress jquery-plugins jquery-autocomplete


    【解决方案1】:

    我会直接使用 json_encode 并简化它:

    <script> 
    $(document).ready(function(){ 
      <?php global $frm_entry_meta; 
      $entries = $frm_entry_meta->get_entry_metas_for_field(37, $order=''); ?> 
      var data = <?php echo json_encode($entries); ?>;
    
      $("#field_name-of-the-school").autocomplete({source: data});
    });  // note you were missing a semicolon at the end of this, which i added
    </script>
    

    当然,如果$entries 是一个关联数组而不是数字索引数组,则使用上述方法可能不是您想要的。如果是这样,您可以这样做json_encode(array_values($entries));

    【讨论】:

      【解决方案2】:

      你必须使用

      $("#field_name-of-the-school").autocomplete({ source : data });
      

      Autocomplete documentation 示例所示。你也可能认为 关于使用JSON

      【讨论】:

        猜你喜欢
        • 2015-06-20
        • 1970-01-01
        • 1970-01-01
        • 2017-07-21
        • 1970-01-01
        • 2012-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多