【问题标题】:how to get ajax suggestions from a text file [duplicate]如何从文本文件中获取 ajax 建议 [重复]
【发布时间】:2016-01-25 13:19:42
【问题描述】:

最近我一直在尝试编写一个系统,其中一个 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>

这里是 gethint.php,它起作用的部分,

<?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;
?>

【问题讨论】:

  • 这里没有使用 JSON 有什么原因吗?
  • $a是目标文件,而不是数组。文件data.txt 的内容是什么?采用哪种格式?
  • 因为我也不知道我也没见过它被使用过
  • 我告诉过你,data.txt 的内容是“john doe”这几个字,而且 php 只是 2 块 php 匆忙拼凑起来的。我刚开始使用php,所以我不太擅长它

标签: php html ajax text


【解决方案1】:

如果可能的话,我会以合适的格式存储名称,例如 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();   
}

【讨论】:

  • 老实说,使用 JSON 而不是每行都有一个名称的文件,您不会获得任何好处。不过,它确实增加了解析 JSON 的额外步骤。只有当输入完全匹配而不是部分匹配时,您的解决方案才会显示建议。
  • @MagnusEriksson 如果我们还处于 20 世纪,那么使用纯文本就可以了。 JSON 更整洁。 @OP 如果您想进行部分搜索而不是完全匹配,请使用strstr()。我回答的目的不是为他/她写OP的代码,只是给他们一个例子。
  • “更整洁”...增加不必要的复杂性的好论据。无论哪个世纪,您都应该始终关注 KISS (en.wikipedia.org/wiki/KISS_principle)。 OP 需要一个名称列表。没有其他属性。在这种特定情况下使用 JSON 将 1. 添加一个会影响性能的额外解析步骤 2. 使文件更大(因为您需要在文件中添加额外的标记)。你有什么收获?是不是有点“整洁”了?
【解决方案2】:

你可以这样做:

$q = $_REQUEST["q"];

//Read file contents as an array
$lines = file("data.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

//Default output
$suggestions = "No suggestions...";

//If the  file is not empty, try to search lines that contains $q
if(!empty($lines)){

    //Search for $q inside a line, case insensitive
    $results = array_filter($lines, function($line){
        return stripos($line, $q) !== false;
    });
    $suggestions = implode(", ", $results);
}

//Output
echo $suggestions;

【讨论】:

  • 为什么 OP 应该尝试这个? 好的答案将始终解释所做的事情以及这样做的原因,不仅适用于 OP,也适用于 SO 的未来访问者。
  • ...加上这个答案每次都会显示文件的全部内容,无论输入如何。
  • 我已经用一些 cmets 更新了我的答案...希望我说得更清楚一点
猜你喜欢
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-12
  • 2015-09-09
  • 2012-04-03
  • 2020-02-11
相关资源
最近更新 更多