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();
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!