php没有从ajax javascript回显任何内容?

时间:2019-01-18 09:04:05

标签: javascript php ajax

当我在搜索字段中输入文本时,我无法使输入回显。 我的确收到了警报JavaScript,但没有将echo 2显示在srv_search_mini_display字段中。 我认为ajax无法访问find_Service.php

search.php

 <input id="service_search_box" class="form-control mr-sm-2" type="text" name="search" placeholder="Search Services..." oninput="searchService()">
 <div id="service_search_div" class="srv_search_mini_display d-none"></div>

<script type="application/javascript">

function searchService(){

    var srv_search = document.getElementById("service_search_box").value;

    var param = "service_search_box="+srv_search;

    if(srv_search.length > 0){

        $("#search_search_div").removeClass("d-none");

        var ajax = new XMLHttpRequest();

        ajax.onreadystatechange = function(){

            if(ajax.readyState === 4 && ajax.status === 200){

                if(ajax.responseText === ""){

                    document.getElementById("service_search_div").innerHTML = "";
                    $("#service_search_div").addClass("d-none");

                } else {

                    alert(param); document.getElementById("service_search_div").innerHTML = ajax.responseText;
                }

            }
        };

        ajax.open("POST",'find_Service.php',false);
        ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        ajax.send(param);

    } else{

        document.getElementById("service_search_div").innerHTML = "";
        $("#service_search_div").addClass("d-none");
    }

}
</script>

find_Service.php

 <?php

 require_once('database.php');
 $heidisql = pdo_con();

 echo 2; // does not even appear
  ?>

1 个答案:

答案 0 :(得分:1)

首先,您必须确保您的PHP文件可以正常工作,您可以单独打开find_Service.php来检查它,也可以像@ADyson所说的那样从网络标签的检查控制台中检查它。

自从我看到您使用jQuery以来,我通过使用jQuery的ajax和带有$符号的select元素来简化了代码。

我使用伪造的API服务器使其在此处运行。

function searchService(){
  var srv_search = $('#service_search_box').val();
  var $srv_search_div = $('#service_search_div');

  if(srv_search.length > 0){
    $("#search_search_div").removeClass("d-none");

    $.post("https://jsonplaceholder.typicode.com/posts", //replace with "/find_Service.php"
    {
      service_search_box: srv_search,
    },
    function(data, status){
      if(status === "success" ){
        $srv_search_div.html(data.service_search_box); //replace with data
        $srv_search_div.addClass("d-none");
      }
      console.log(data);
    });

  }else{
    $srv_search_div.html("");
    $("#service_search_div").addClass("d-none");
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input id="service_search_box" class="form-control mr-sm-2" type="text" name="search" placeholder="Search Services..." oninput="searchService()">
 <div id="service_search_div" class="srv_search_mini_display d-none"></div>