使用嵌入式PHP将jQuery函数插入Wordpress单页中


Inserting jQuery function into Wordpress single page with embedded PHP

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

这是我在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
    );
}

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

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

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

  3. 您已经在输入文件中提到了自动完成,所以您应该在js片段中使用类似的onkeyuponkeypress事件。

然而,你应该分别学习整体的东西,然后按照你的期望去执行。

global $wpdb;
$results = $wpdb->get_results( "SELECT col FROM table");
foreach ($results as $tableResult)
{
    echo $tableResult->col;
}