如何从json编码数组中获取特定值?

时间:2015-01-08 18:15:17

标签: javascript php json

这是我用于动态ajax搜索的JavaScript和PHP。我试图从数据库中获取数据并将其作为字符串显示在我的DOM中。

的javascript

var searchBox = document.getElementById("searchBox");
var searchButton = document.getElementById("searchButton");
var search = getXmlHttpRequestObject();

searchBox.addEventListener("keyup", ajaxSearch);

function getXmlHttpRequestObject(){
  if(window.XMLHttpRequest){
    return new XMLHttpRequest();
  }
  else if (window.ActiveXObject){
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
  else{
    alert("Your browser does not support our dynamic search");
  }
}

function ajaxSearch(){
  var str = escape(document.getElementById('searchBox').value);
  search.open("GET", '../searchSuggest.php?search=' + str, true);
  search.send(null);
  delay(displaySuggestions);
}

function displaySuggestions(){
  var ss = document.getElementById("searchSuggestion");
  ss.innerHTML = '';
  string = search.responseText;
  ss.innerHTML = string;
}


function delay(functionName){
setTimeout(functionName, 100);
}

function setSearch(x){
  document.getElementById("searchBox").value = x;
  document.getElementById("searchSuggestion").innerHTML = "";
}

searchBox.addEventListener('click', ajaxSearch);
window.addEventListener('click', function(){
  document.getElementById('searchSuggestion').innerHTML = '';
  });

PHP

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Products";

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $searchValue = $_GET['search'];

  if(isset($searchValue) && $searchValue != ''){
    $search = addslashes($searchValue);
    $statement = $conn->prepare("SELECT Name FROM Product WHERE Name LIKE('%" . $search . "%') ORDER BY
    CASE WHEN Name like '" . $search . " %' THEN 0
    WHEN Name like '" . $search . "%' THEN 1
    WHEN Name like '% " . $search . "%' THEN 2
    ELSE 3
    END, Name");
    $statement->execute();


    $result = $statement->fetchAll(PDO::FETCH_ASSOC);
    $json = json_encode($result);
    echo $json;

  }
}
catch(PDOException $e)
{
  echo "Error: " . $e->getMessage();
}

$conn = null;
?>

我想知道如何从我的回复中获取具体的价值。

[{"Name":"iMac"},{"Name":"iPad 2"},{"Name":"iPhone 5"},{"Name":"iPhone 6"},{"Name":"iPod Touch"},{"Name":"iWatch"}]

为了使我的搜索工作有效,我需要它只显示产品名称的字符串,而不是整个对象。

1 个答案:

答案 0 :(得分:0)

使用延迟而不是ajax回调很容易失败。假设您的ajax调用超过100毫秒?它完全可以发生。同样,如果您的服务器很好而且速度很快并且它在25年结束,为什么要等待100毫秒?

抛弃全局search对象,并更改此内容:

function ajaxSearch(){
  var str = escape(document.getElementById('searchBox').value);
  search.open("GET", '../searchSuggest.php?search=' + str, true);
  search.send(null);
  delay(displaySuggestions);
}

function ajaxSearch(){
  var str = escape(document.getElementById('searchBox').value);
  var search = getXmlHttpRequestObject();
  if (search) {
    search.onreadystatechange = function() {
        if (search.readyState == 4 && search.status == 200) {
            displaySuggestions(JSON.parse(search.responseText));
        }
    };
    search.open("GET", '../searchSuggest.php?search=' + str, true);
    search.send(null);
  }
}

然后displaySuggestions收到一个数组:

function displaySuggestions(results) {
  // Use standard array techniques on `results`, e.g., `results[0]` is the first,
  // maybe loop while `index < results.length`, maybe use `results.forEach(...)`...
}

或者更进一步,让我们在那里增加一些便利:

var failed = false;
function getXmlHttpRequestObject(done, failed){
  var xhr;

  if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
  }
  else if (window.ActiveXObject){
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }
  else {
    if (!failed) {
      alert("Your browser does not support our dynamic search");
      failed = true;
    }
    return null;
  }

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200 {
        if (done) {
          done(xhr);
        }
      } else {
        if (failed) {
          failed(xhr);
        }
      }
    }
  };

  return xhr;
}

然后:

function ajaxSearch(){
  var str = escape(document.getElementById('searchBox').value);
  var search = getXmlHttpRequestObject(function(xhr) {
    displaySuggestions(JSON.parse(xhr.responseText));
  });
  if (search) {
    search.open("GET", '../searchSuggest.php?search=' + str, true);
    search.send(null);
  }
}