Javascript 提交搜索查询并在不刷新的情况下获取搜索结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3074380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:11:48  来源:igfitidea点击:

Submit Search query & get Search result without refresh

phpjavascriptjquery

提问by MANnDAaR

I want to submit search queryform & get search resultwithout redirecting/reloading/refreshingon the same page.

我想提交搜索查询表单并获取搜索结果,而无需在同一页面重定向/重新加载/刷新

My content is dynamic so can not use those "submit contact form without refreshing page which replies back on success".

我的内容是动态的,所以不能使用那些“提交联系表格而不刷新页面,成功回复”。

回答by Zuul

In order to submit a form, collect the results from the database and present them to the user without a page refresh, redirect or reloading, you need to:

为了提交表单,从数据库中收集结果并将它们呈现给用户,而无需刷新、重定向或重新加载页面,您需要:

  1. Use Ajax to Post the data from your form to a php file;

  2. That file in background will query the database and obtain the results for the data that he as received;

  3. With the query result, you will need to inject it inside an html element in your page that is ready to present the results to the user;

  4. At last, you need to set some controlling stuff to let styles and document workflow run smoothly.

  1. 使用 Ajax 将表单中的数据发布到 php 文件;

  2. 后台的那个文件会查询数据库,得到他收到的数据的结果;

  3. 对于查询结果,您需要将其注入页面中准备向用户呈现结果的 html 元素中;

  4. 最后,你需要设置一些控制的东西,让样式和文档工作流顺利运行。



So, having said that, here's an working example:

所以,话虽如此,这是一个工作示例:

We have a table "persons" with a field "age" and a field "name" and we are going to search for persons with an age of 32. Next we will present their names and age inside a divwith a tablewith pink background and a very large text.
To properly test this, we will have an header, body and footer with gray colors!

我们有一个表“人”与现场“年龄”和“name”字段,我们要寻找的人与32接下来的时代,我们将提出内他们的名字和年龄divtable粉红色背景和非常大的文本。
为了正确测试这一点,我们将有一个灰色的页眉、正文和页脚!

index.php

索引.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html lang="pt" dir="ltr">

  <head>

    <title>Search And Show Without Refresh</title>

    <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
    <meta http-equiv="Content-Style-Type" content="text/css">

    <!-- JQUERY FROM GOOGLE API -->
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

    <script type="text/javascript">
      $(function() {
        $("#lets_search").bind('submit',function() {
          var value = $('#str').val();
           $.post('db_query.php',{value:value}, function(data){
             $("#search_results").html(data);
           });
           return false;
        });
      });
    </script>

  </head>

  <body style="margin:0;padding:0px;width:100%;height:100%;background-color:#FFFFFF;">

    <div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
      HEADER
    </div>
    <div style="width:1024px;margin:0 auto;height:568px;background-color:#f0f0f0;text-align:center;">
      <form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
        Search:<input type="text" name="str" id="str">
        <input type="submit" value="send" name="send" id="send">
      </form>
      <div id="search_results"></div>
    </div>
    <div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
      FOOTER
    </div>

  </body>

</html>

db_query.php

db_query.php

<?php

define("HOST", "localhost");

// Database user
define("DBUSER", "username");

// Database password
define("PASS", "password");

// Database name
define("DB", "database_name");

// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');

############## Make the mysql connection ###########

$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);

$db = mysql_select_db(DB) or die(DB_MSG_ERROR);


$query = mysql_query("
  SELECT * 
  FROM persons 
  WHERE age='".$_POST['value']."'
");

echo '<table>';

while ($data = mysql_fetch_array($query)) {

  echo '
  <tr style="background-color:pink;">
    <td style="font-size:18px;">'.$data["name"].'</td>
    <td style="font-size:18px;">'.$data["age"].'</td>
  </tr>';

}

echo '</table>';

?>

The controlling stuff depends from what you want, but use that code, place those two files in the same directory, and you should be fine!

控制内容取决于您想要什么,但是使用该代码,将这两个文件放在同一目录中,您应该没问题!

Any problems or a more explicative code, please let us know ;)

任何问题或更详细的代码,请告诉我们;)

回答by Jamie Wong

This is what AJAX is for. In jQuery (apologies if you're looking for a different library)

这就是 AJAX 的用途。在 jQuery 中(抱歉,如果您正在寻找不同的库)

$("form#search").bind('submit',function() {
  $.post("search.php",this.serialize(),function(data) { 
    // Put the code to deal with the response data here
  });
  return false;
});

回答by desau

You'll probably want to start with any of the thousands of "AJAX for beginners" tutorials you can find on the net. A Google search with that term should get you going.

您可能想从网上可以找到的数千个“AJAX 初学者”教程中的任何一个开始。使用该词的 Google 搜索应该会让您有所了解。

Try this for starters:

初学者试试这个:

http://www.destraynor.com/serendipity/index.php?/archives/29-AJAX-for-the-beginner.html

http://www.destraynor.com/serendipity/index.php?/archives/29-AJAX-for-the-beginner.html

After you've read through that, keep in mind that you really don't need to be writing any XHR handling code. As pointed out by Jamie, jQuery or any of the other multitudes of Javascript libraries out there, can greatly simplify your client-side AJAX code.

在您通读之后,请记住您真的不需要编写任何 XHR 处理代码。正如 Jamie 所指出的那样,jQuery 或其他众多 Javascript 库中的任何一个都可以极大地简化您的客户端 AJAX 代码。

回答by Wind Chimez

It's good if you can get some basics of Ajax before straight away going to the code. Ajax , is the exact solution for your problem. It asynchronously makes a request to the server, get the result and the data in the page can be modified with the result . It's all done in JavaScript.

如果您能在直接阅读代码之前了解一些 Ajax 基础知识,那就太好了。Ajax 是您问题的确切解决方案。异步向服务器发出请求,获取结果,页面中的数据可以通过结果进行修改。这一切都是在 JavaScript 中完成的。

Suppose you have an html like this:

假设你有一个这样的 html:

<html>
<body>
<div id="myDiv"> your content area</div>
<button type="button" onclick="loadByAjax()">Change Content</button>
</body>
</html> 

Now, your javascipr code will be like this:

现在,您的 javascipr 代码将如下所示:

<script type="text/javascript">
function loadByAjax()
{
     $.ajax({
          type: "POST",
          url: "yourserverpage.php",
          data: "searchkey=data_from_user_input",
          success: function(response_data){
          $('myDiv').html(response_data)
          }
          });
}
</script>

so, basically upon click of the button, the JavaScript will be executed. It wil call the php serverside script, pass the parameters it got from user input and retrieve the response data and place it inside the div. So your page is updated without full refresh.

所以,基本上只要点击按钮,JavaScript 就会被执行。它将调用 php 服务器端脚本,传递它从用户输入中获得的参数并检索响应数据并将其放置在 div 中。因此,您的页面无需完全刷新即可更新。

Also, please understand that, i used jquery library here for the Ajax function.

另外,请理解,我在这里使用了 jquery 库作为 Ajax 函数。