【问题标题】:Inserting jQuery function into Wordpress single page with embedded PHP使用嵌入式 PHP 将 jQuery 函数插入 Wordpress 单页
【发布时间】:2015-02-27 21:47:12
【问题描述】:

我正在尝试将 jQuery 函数插入到连接到 MySQL 数据库的 Wordpress 页面中,该数据库返回大量项目列表,用于表单中的自动完成文本输入。它不工作。

这是我在我正在使用的主题的文件结构中创建的 js 文件夹中自己的 .js 文件中的函数:

jQuery(document).ready(function($) {

$(

    var availableTags = [

    <?php

    $dbh=mysql_connect ("localhost", "db_name", "db_name") or die ('I cannot connect to the database because: ' . mysql_error());
    mysql_select_db ("db_name") or ("Database not found");

    $query = "SELECT col FROM table";
    $result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());

    while ($row = mysql_fetch_array($result)) {
    echo "\"". $row['col']."\", ";
    }

    // $result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());

    mysql_close($connect);

    ?>
    ];

    $( "#id" ).autocomplete({
    source: availableTags

    });

)});

这些是外部链接:

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>

这是我在主题的 functions.php 文件中插入的内容:

add_action( 'wp_enqueue_scripts', 'add_my_script' , 11 );
function add_my_script() {
    wp_enqueue_script(
        'function_name', 
        get_template_directory_uri() . '/js/function_name.js',
        array('jquery'),
        '1.0',
        true

    );
}

【问题讨论】:

  • 能解释一下“不工作”是什么意思吗?错误,错误的格式,....
  • 你不能在 js 文件中运行 php 代码。服务器不会编译它
  • 您直接包含 jquery,然后将其添加为入队脚本的要求。取出链接,wordpress 不需要它们。另外,正如@charlietfl 所说,您不能从 js 表单中编译 php,因为 php 是在服务器端编译的,而 js 是在运行时编译的。
  • 这段代码在本地工作,PHP嵌入在jquery中,jquery嵌入在
  • 感谢您的反馈,但有哪些解决方案?任何指向教程或视觉效果的链接?

标签: php jquery wordpress wordpress-theming


【解决方案1】:

您不能在 javascript 文件中运行 php 代码。那么你应该怎么做:

  1. 你应该使用ajax,首先学习如何在wordpress中使用ajax。参考例子:http://www.smashingmagazine.com/2011/10/18/how-to-use-ajax-in-wordpress/

  2. Wordpress 已经有数据库连接,你不应该重新连接。只是你只会做查询。这是在 wordpress 中如何查询和其他查询相关的类参考:http://codex.wordpress.org/Class_Reference/wpdb

  3. 您已经在输入字段中提到了自动完成功能,因此您应该在 js sn-p 中使用 onkeyuponkeypress 类似的事件。

但是,你应该单独学习整体的东西,然后按照你的期望去执行。

【讨论】:

    【解决方案2】:
    global $wpdb;
    
    $results = $wpdb->get_results( "SELECT col FROM table");
    foreach ($results as $tableResult)
    {
        echo $tableResult->col;
    }
    

    【讨论】:

    • 是的,但是如何在 HTML 表单中获取文本字段以在用户开始输入时自动填充这些值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多