使用PHP作为源代码的Jquery自动完成无法工作

Jquery autocomplete with PHP as a source not working

本文关键字:工作 Jquery PHP 源代码 使用      更新时间:2023-09-26

我是jQuery的新手,正在尝试在文本框中设置一个简单的自动完成。我的代码如下:

HTML:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
    $( "#searchstr" ).autocomplete(
    {
         source:'searchjson.php',
    })
});
</script>
<?php 
include('code.php') ;
show_header();
?>
<title>CodeLib</title>
</head>
<body>
    <div><h3>Welcome to CodeLib.com.au</h3><div>
    <h4>Articles</h4>
    <form action="index.php" method="get">
        <div class="ui-widget" >Search:(4 chars min) <input name="searchstr" id="searchstr" type="text" /></div>
</form>
</body>

我的PHP代码是:

<?php
include("code.php");
// if the 'term' variable is not sent with the request, exit
if ( !isset($_REQUEST['searchstr']) )
    exit;
open_db();
// query the database table for zip codes that match 'term'
$rs = mysql_query('select article_title from articles where article_title like "'. mysql_real_escape_string($_REQUEST['searchstr']) .'%" limit 10');
// loop through each zipcode returned and format the response for jQuery
$data = array();
$str = "";
if ( $rs && mysql_num_rows($rs) )
{
    while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
    {
        $data[] = array('label' => $row['article_title']);
    }
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>

需要注意的几点:

我已经使用固定值测试了脚本,并更改了源代码,如下所示。source: availableTags并在JS中分配固定值-Works fine

用查询字符串中传递的字符串测试了PHP,结果如下:

[{"label":"Simple HTML rich text editor for your web page"}]

但问题是,当我将源代码分配给php代码时,我没有得到。有人能给我线索吗??

非常感谢。

您收到任何javascript错误吗?

使用jQuery尝试使用

$(document).ready(function() {
    .. Your autocomplete code here
});

而不是$(function() {});

这样$('#searchstr')元素将存在

在源代码部分有一个尾随逗号(尤其是在使用IE的情况下)可能很容易。试试这个,它可能会起作用:

<script>
$(function() {
    $( "#searchstr" ).autocomplete(
    {
         source:'searchjson.php' //No comma at the end of this line
    })
});
</script>