【问题标题】:noob question about autosuggest jquery plugin关于自动建议 jquery 插件的菜鸟问题
【发布时间】:2011-07-13 04:30:02
【问题描述】:

我想为我的文本字段做一些自动建议,使用这个插件AutoSuggest jQuery Plugin

我有一个数组,已经 json_encoded,以及服务器上的文件,js,css,但我还没有了解示例的工作原理,这里是我的代码,

<html>
 <head>
  <title>test-data</title>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <link href="inc/css/admin_style.css" rel="stylesheet" type="text/css">
     <link href="inc/css/autoSuggest.css" rel="stylesheet" type="text/css">
     <script language="javascript" src="inc/js/functions.js"></script>
     <script language="javascript" src="inc/js/jquery-1.5.1.js"></script>
     <script language="javascript" src="inc/js/jquery.autoSuggest.js"></script>
     <script language="javascript" type="text/javascript">
      </script>
 </head>

 <body>
 <center><br><font class="title">test</font></center>

  <form action="dataAll.php" method="post">
   Name: <input type="text" name="fname" />
  <input type="submit" />
   </form>

   <p>&nbsp;</p>
  <p>JSON</p>
  <p>&nbsp;</p>
  <?php
  $encoded =  json_encode ($familyNames);
  echo $encoded;
   ?>
  </body>
  </html>

所以我应该把这段代码,

 $(function(){
 $("input[type=text]").autoSuggest(data);
 });
  • 但问题是在哪里??(好像我把它放在php标签内,它给了我一个错误
  • 我应该将我的 json 格式数组的名称放在哪里? "$encoded" 让函数识别这是数据源吗?

非常感谢!

【问题讨论】:

    标签: php json autosuggest


    【解决方案1】:

    你已经得到了所有的东西,但是你的顺序/方法有点不对劲。尝试创建第二个文件,命名为 ajax.php,然后将所有 php 代码放在其中。为确保您输出良好的 JSON,请在 ajax.php 文件的最开头添加行 header('Content-Type: text/json; charset=ISO-8859-1');(您必须在发送任何输出之前设置标题 否则您会收到错误消息) .现在您必须请求您的建议数据:

    $(document).ready(function() {   // Runs when your page is loaded in the user's browser
        $.getJSON('ajax.php', function(data) { // Runs ajax.php, then executes an anonymous function to handle the response
            $('input[name="fname"]').autoSuggest(data); // Set your input field to use automatic suggestions with the returned data
        }); // end getJSON
    }); // end ready
    

    此代码只是对ajax.php 执行异步HTTP 请求,并将返回的JSON 数据交给自动建议的jQuery 插件。将其放在&lt;script type="text/javascript"&gt;&lt;/script&gt; 标记内。由于使用$(document).ready(...),它将在页面加载时运行一次。我添加了小优化 (input[name="fname"]),因此 jQuery 不会尝试将自动建议功能附加到页面上的每个文本输入。如果那是您想要做的(不太可能),只需将其改回input[type=text]

    你真的不需要一个单独的 php 文件来让它工作。没有什么可以阻止您在一个文件中完成所有操作,但是您很快就会意识到这会变得多么混乱和难以管理。对我来说,最容易将我的“ajaxy”php 代码视为我的 Web 应用程序的单个模块化部分。

    请务必参考这些页面以获取详细信息:

    【讨论】:

      【解决方案2】:

      你把它放在 html 的标签内。

      <script type="text/javascript">
       $(function(){
       $("input[type=text]").autoSuggest(data);
       });
      </script>
      

      【讨论】:

      • 嗨,谢谢,我试过了,在标题和正文中,现在没有错误,但是自动建议不起作用,自动建议如何知道要使用哪个 json 源?我错过了什么? tnx!
      猜你喜欢
      • 1970-01-01
      • 2020-09-13
      • 2011-10-24
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多