如何使用jQuery / Ajax发布搜索表单并将结果放入div?

时间:2015-06-04 03:34:26

标签: javascript jquery ajax forms post

我尝试将搜索查询发布到本地服务器,并使用Ajax将结果返回到div中。我按照文档中的公式但无法获得输出。也没有得到任何控制台日志错误。源代码来自:Post a form using ajax and put results in a div

<form action="/" id="searchForm">
   <input type="text" name="s" placeholder="Search...">
   <input type="submit" value="Search">
</form>
  <!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<p id="content">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>
<script>
$(document).ready(function () {

$("#searchForm").submit(function(event) {

  // Stop form from submitting normally
  event.preventDefault();

  // Get some values from elements on the page:
  var $form = $(this),
    term = $form.find( "input[name='s']").val(),
    url = $form.attr("action");

  // Send the data using post
  var posting = $.post( url, {s: term});

  // Put the results in a div
  posting.done(function(data) {
    var content = $(data).find("#content");
    $("#result").empty().append(content);
  });
 });
});  
</script>

2 个答案:

答案 0 :(得分:0)

Code Specifically for you Plunker

<强> JS

// Code goes here
$(document).ready(function() {
  $("#searchForm").submit(function(event) {
    // Stop form from submitting normally
    event.preventDefault();

    // Get some values from elements on the page:
    var $form = $(this),
      term = $form.find("input[name='s']").val(),
      url = $form.attr("action");

    // Send the data using post

    var posting = $.post(
      url, {
        s: term
      },
      myPostWasSuccessful,
      'html'
    );
  });
});

function myPostWasSuccessful(data, textStatus, jqXHR) {
  $("#result").html(data);
}

<强> HTML

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>

<body>
  <form action="/" id="searchForm">
    <input type="text" name="s" placeholder="Search...">
    <input type="submit" value="Search">
  </form>
  <!-- the result of the search will be rendered inside this div -->
  <div id="result"></div>
  <p id="content">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
  </p>
</body>

</html>

jQuery Post Documentation

我们使用dataType函数的success$.post个参数。

  

<强>成功

     

类型:功能(对象数据,字符串textStatus,jqXHR jqXHR)

     

请求成功时执行的回调函数。如果提供了dataType,则是必需的,但在这种情况下可以为null。

     

<强>的dataType

     

类型:字符串

     

服务器所需的数据类型。默认值:智能猜测(xml,json,脚本,文本,html)。

答案 1 :(得分:0)

您可以使用html()方法,即:

var content = data;
console.log(data);
$("#result").html(content);