简体   繁体   English

使用ajax根据搜索结果显示结果?

[英]using ajax to display results depending on search?

So currently, I have a php page which displays a list of results which it gets from my sql database. 因此,目前,我有一个php页面,其中显示了从sql数据库获取的结果列表。 It displays the ID and the names. 它显示ID和名称。

I have a search at the top which just searches for keywords in the "name" field then if search is clicked it will take you to a new page which shows the results you have searched for. 我在顶部进行搜索,仅在“名称”字段中搜索关键字,然后单击搜索将带您到一个新页面,该页面显示了您搜索的结果。

What I am trying to do is to make it Asynchronous so when I search for lets say "London" it displays only results which have the keyword London in it, but on the same page. 我想做的是使其异步,因此当我搜索让我说“伦敦”时,它只在其中包含关键字伦敦的结果显示在同一页面上。

My search button code: 我的搜索按钮代码:

    <input type="button" class="search" value= "Search">

Ajax code which I have tried using to make it asynchronous: 我尝试过使用使其异步的Ajax代码:

 $(document).ready(function() {
 $(".search").each(function() {
 var btn = $(this);
 btn.on("click", function(){
 $.post("searchresults.php",
 function(data){
 .append(data);}
 }}})

I'm new to this so apologies if it's a silly mistake. 我对此很陌生,所以很抱歉这是一个愚蠢的错误。 My searchresults.php just has the SELECT * FROM Property WHERE etc.. and then it echos the results. 我的searchresults.php仅具有SELECT * FROM Property WHERE等。然后,它回显结果。

Thanks. 谢谢。

You need to have some element on your page that'll hold the search results, eg 您需要在页面上有一些元素来保存搜索结果,例如

<div id="result"></div>

and then in your .post() call, you'd have a result handler that does 然后在您的.post()调用中,您将有一个结果处理程序

function (results) {
    $('#result').text(results);
}

Exactly how you actually insert/display the data is up to you - your PHP script could send over a full-blown html snipper, or a nice JSON-encoded data structure and your JS builds up the results, etc... This is just a simple brain-dead "here's some result data and display it as-is". 实际插入/显示数据的方式完全由您决定-您的PHP脚本可以通过完整的html截屏器发送,也可以通过漂亮的JSON编码的数据结构发送,而JS可以建立结果,等等。一个简单的大脑死亡,“这里有一些结果数据并按原样显示”。

//Function to call when button is clicked //点击按钮时调用的函数

function getData(){

    //declare any vars you want here
    var variable1='variable1Content';
    var variable2='variable2Content';

    //Post some data to your php script without reloading the page
    $.post('getData.php',{var1:variable1,var2:variable2},function(data){ 

        $("#targetDiv").empty().append(data);
    });
}

data is the response of php script (may be html code in this case) 数据是php脚本的响应(在这种情况下,可能是html代码)

var1 & var2 are the names you will find in $_POST vars in php script var1和var2是您将在$ _POST php脚本中找到的名称

"targetDiv" is the id of the target div in wich you will put your content. “ targetDiv”是目标div的ID,您将在其中放置内容。

Queries are done in your php script. 查询是在您的php脚本中完成的。

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

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