我尝试将搜索查询发布到本地服务器,并使用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>
答案 0 :(得分:0)
<强> 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>
我们使用dataType
函数的success
和$.post
个参数。
<强>成功强>
类型:功能(对象数据,字符串textStatus,jqXHR jqXHR)
请求成功时执行的回调函数。如果提供了dataType,则是必需的,但在这种情况下可以为null。
<强>的dataType 强>
类型:字符串
服务器所需的数据类型。默认值:智能猜测(xml,json,脚本,文本,html)。
答案 1 :(得分:0)
您可以使用html()
方法,即:
var content = data;
console.log(data);
$("#result").html(content);