douejuan9162 2016-10-30 12:49
浏览 40

Ajax Live Search Javascript数据

function getData(str) {
if (str.length == 0) { 
    var target = document.querySelectorAll("#delete");
    return;
} else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var target = document.querySelectorAll("#delete");
            for(var i=0 ; i<target.length; i++){
                target[i].innerHTML="";
                target[0].innerHTML=this.responseText;

            }


        } 
    };
    xmlhttp.open("GET", "data.php?q=" + str, true);
    xmlhttp.send();
}

}

Good morning, I have the following javascript for AJAX request on a live search. I then send this data to data.php page that checks if get request of q is empty and if its not, matching data is returned. Now, when the search box is empty, I want to show all results instead of showing no results. I tried checking if $_GET request is empty on the data.php page to output all results but it's not working. The only way I seem to be able to do something when $_GET['q'] is empty is in the javascript above in the

if(str.length==0) {
 .... 
} ; 

Now the problem I have is that I want to send all the data if search is empty but that data is in my php file so how would I send the data from php to javascript? There may be a better way to do this or is there something I don't get here?

  • 写回答

1条回答 默认 最新

  • doushangan3690 2016-11-01 06:32
    关注

    If you want to show all search results when the search string is empty, then you can just check in data.php if the q parameter of $_GET is empty. If it is empty then data.php can return all the data. Your code can be updated as follows:

    function getData(str) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var target = document.querySelectorAll("#delete");
                for(var i=0 ; i<target.length; i++){
                    target[i].innerHTML="";
                    target[0].innerHTML=this.responseText;
    
                }
    
    
            } 
        };
        xmlhttp.open("GET", "data.php?q=" + str, true);
        xmlhttp.send();
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计