简体   繁体   English

如何使用jquery ajax获取php URL的json_encode数据?

[英]How to get json_encode data of php url using jquery ajax ?

autocomplete-api.php 自动完成,api.php

<?php
    session_start();
    error_reporting(0);
    include("includes/config.php");

    $data = array();
    $query = "SELECT product_name FROM inventory group by product_name;";
    $query .= "SELECT name FROM brands;";
    $query .= "SELECT name FROM categories;";

    mysqli_multi_query($con,$query);
    $result = mysqli_store_result($con);

    while($row = mysqli_fetch_assoc($result)) 
    {
        $data[] = array(
                        'products' => $row['product_name']
                    );
    }

    mysqli_free_result($result);
    mysqli_next_result($con);

    $result = mysqli_store_result($con);

    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = array(
                        'products' => $row['name']
                    );
    } 

    mysqli_free_result($result);
    mysqli_next_result($con);

    $result = mysqli_store_result($con);

    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = array(
                        'products' => $row['name']
                    );
    } 

    mysqli_free_result($result);
    mysqli_close($con);

    $results = json_encode($data);
    print($results);
?>

autocomplete.js autocomplete.js

function autocomplete(inp, arr) {
  var currentFocus;
  inp.addEventListener("input", function(e) {
      var a, b, i, val = this.value;
      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;
      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");
      this.parentNode.appendChild(a);
      for (i = 0; i < arr.length; i++) {
        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          b = document.createElement("DIV");
          b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i].substr(val.length);
          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
          b.addEventListener("click", function(e) {
              inp.value = this.getElementsByTagName("input")[0].value;
              closeAllLists();
          });
          a.appendChild(b);
        }
      }
  });
  inp.addEventListener("keydown", function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {
        currentFocus++;
        addActive(x);
      } else if (e.keyCode == 38) {
        currentFocus--;
        addActive(x);
      } else if (e.keyCode == 13) {
        e.preventDefault();
        if (currentFocus > -1) {
          if (x) x[currentFocus].click();
        }
      }
  });
  function addActive(x) {
    if (!x) return false;
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    x[currentFocus].classList.add("autocomplete-active");
  }
  function removeActive(x) {
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }
  function closeAllLists(elmnt) {
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
        x[i].parentNode.removeChild(x[i]);
      }
    }
  }
  document.addEventListener("click", function (e) {
      closeAllLists(e.target);
      });
}
$.ajax({
    type:"GET",
    url:"http://localhost/leafteaculture/autocomplete-api.php",
    datatype:"JSON",
    success:function(json){
        alert(json);
        /*$.each(json, function(key, item) {
            var countries =  item.products;
            alert(countries);
        });*/
    }
});

Index.php 的index.php

<input type="text" name="pro_duct" id="pro_duct" />

<script src="<?php echo $base_url; ?>assets/js/autocomplete.js"></script>
<script>
    autocomplete(document.getElementById("pro_duct"), countries);
</script>

Possible might be duplicate question. 可能是重复的问题。 I have created autocomplete suggestion box where I have autocomplete-api.php where I have used json_encode function which is working fine but problem with autocomplete.js file. 我创建了自动完成建议框,在其中有autocomplete-api.php ,在其中使用了json_encode函数,该函数工作正常,但autocomplete.js文件存在问题。 I am unable to get data from autocomplete-api.php file. 我无法从autocomplete-api.php文件中获取数据。 I want to fetch data from autocompelete-api.php url and put it into the jquery variable. 我想从autocompelete-api.php网址中获取数据并将其放入jquery变量中。 So, How can I do this? 那么,我该怎么做? Please help me. 请帮我。

Thank You 谢谢

The possible problem might be that since you've used json_encode which returns a string and in the AJAX request you've specified the dataType to be JSON , AJAX is unable to find the required dataType in the response. 可能的问题是,由于您使用了返回string json_encode ,并且在AJAX请求中将dataType指定为JSON ,因此AJAX无法在响应中找到所需的dataType。 You could simply remove the dataType property from the AJAX request. 您可以简单地从AJAX请求中删除dataType属性。 Once the data is fetched, you need to use JSON.parse to convert the string to JSON format. 提取数据后,您需要使用JSON.parse将字符串转换为JSON格式。

Refer to AJAX documentation and json_encode for more info. 有关更多信息,请参考AJAX文档和json_encode

Hope this helps. 希望这可以帮助。

I think the first thing to fix is your php file -- let's boil that thing down. 我认为要修复的第一件事是您的php文件-让我们将其归结为下来。 You can maintain the same query logic / resulset with much less hassle by using UNION keywords to form a single / more efficient query. 通过使用UNION关键字形成单个/更有效的查询,您可以维护相同的查询逻辑/结果集,而麻烦却更少。

session_start();
header('Content-type: application/json');
include("includes/config.php");

if (!$result = $con->query("(SELECT product_name AS products FROM inventory GROUP BY product_name) UNION (SELECT name FROM brands) UNION (SELECT name FROM categories)")) {
    echo [];  // check $con->error; because your query failed
} else {
    echo json_encode($result->fetch_all(MYSQLI_ASSOC));
}

Yes, it really can be reduced THAT much! 是的,确实可以减少很多! Here's proof that the query works . 这是查询有效证明

From the same data, here is the generated json string: 根据相同的数据,这是生成的json字符串:

[{"products":"One"},{"products":"Three"},{"products":"Two"},{"products":"Four"},{"products":"Five"},{"products":"Six"},{"products":"Seven"},{"products":"Eight"}]

Then, then the json string is received by your javascript, call var apiArray = = JSON.parse(json); 然后,您的JavaScript接收到json字符串,调用var apiArray = = JSON.parse(json); so that you can work with the multi-dimensional array containing a single column of data. 因此您可以使用包含单列数据的多维数组。


...ps If you are worried about duplicate product names, you can weed out duplicates in the query: ... ps如果您担心商品名称重复,可以在查询中淘汰重复的商品:

SELECT DISTINCT product FROM (
    (SELECT product_name AS product FROM inventory GROUP BY product_name)
    UNION
    (SELECT name FROM brands)
    UNION
    (SELECT name FROM categories)
) Unionized

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM