如何从文本文件中获取ajax建议

时间:2016-01-25 13:19:42

标签: php html ajax text

最近我一直在尝试编写一个系统,其中一个php文件读取一个充满名字的文本文件(现在我只是把john doe)并将其显示为自动完成文本。这是我在html中尝试的内容:



function showHint(str) {
  var xhttp;
  if (str.length == 0) { 
    document.getElementById("txtHint").innerHTML = "";
    return;
  }
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("txtHint").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "gethint.php?q="+str, true);
  xhttp.send();   
}

<!DOCTYPE html>
<html>
<body>

<h3>Start typing a name in the input field below:</h3>

<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>

<p>Suggestions: <span id="txtHint"></span></p> 
  </body>
  </html>
&#13;
&#13;
&#13;

这里是gethint.php,是剂量工作的部分,

&#13;
&#13;
<?php
// Array with names
$a = fopen("data.txt", "r") or die("Unable to open file!");
echo fread($a,filesize("data.txt"));
fclose($a);

// get the q parameter from URL
$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from "" 
if ($q !== "") {
    $q = strtolower($q);
    $len=strlen($q);
    foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
                $hint = $name;
            } else {
                $hint .= ", $name";
            }
        }
    }
}

// Output "no suggestion" if no hint was found or output correct values 
echo $hint === "" ? "no suggestion" : $hint;
?>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

你可以这样做:

from django.utils.text import Truncator
value = Truncator(value).chars(75)

答案 1 :(得分:0)

如果可能,我会以合适的格式存储名称,例如JSON:

data.json:

["Nav", "bob", "John"]

然后加载名称很简单:

gethint.php

 $names = json_decode(file_get_contents('data.json'), true);
 $output = array();
 $q = $_REQUEST["q"]

foreach($names as $name) {
  if ($name == $q) {
    $output[] = $name
  }
}

// output the results as JSON
echo json_encode($output);

然后你可以使用JSON.parse()解析JS中的JSON并用它做任何事情:

function showHint(str) {
  var xhttp;
  if (str.length == 0) { 
    document.getElementById("txtHint").innerHTML = "";
    return;
  }
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      var results = JSON.parse(xhttp.responseText);
      // Do whatever with results
    }
  };
  xhttp.open("GET", "gethint.php?q="+str, true);
  xhttp.send();   
}