对于客户端:
HTML
<form id="target" action="/search/results">
<input type="text" id="searchText" />
<div id="container"></div>
<input type="hidden" id="searchId" name="searchId" value="">
<button id="btnSearch">Search</button>
</form>
JS
$(document).ready(function() {
$('#btnSearch').click(function(){
$.ajax({
type: 'post',
url: '/process/search',
beforeSend: function () {
$('#container').html('Loading...');
},
data:{"searchText":$("#searchText").val()},
success: function(result) {
$("#searchId").val(result);
$("#target").submit();
},
error: function(error) {
$('#container').html('Search process error...');
}
});
});
});
我不习惯django,但是对于后端,您需要检查请求是如何执行的。
- 服务器在执行搜索的时间是否持有 http 响应
- 或者发送 200/OK 然后运行搜索
EDIT(在 cmets 之后):客户端被编辑(上图)。同样,我不习惯 Django 也不习惯 Python,所以请看下面的某种服务器端代码(类似 NodeJ)。
路由器.JS
//The variables below live and last with HTTPServer (!!not Request!!)
var search = require("my_super_search_module").search;
var contentProvider = require("my_super_content_provider").contentProvider ;
//Used to generate a random unique code to store search result
var guidGen = require("guidGenerator");
//Store search result between the two requests.
var pendingSearch = Array;
//First function called on incoming request
//route contains the url path (without domain)
//postData is parsed to object
//response would be an HTTPresponse provider
function onRequest(route,postData,response)
{
switch(route)
{
case "/process/search":
//callbackSearch function called when search finished
function callbackSearch(error,result)
{
if(error)
{
response.writeAndEnd(error.message,503,"text/json");
return;
}
//e.g. 3F2504E0-4F89-41D3-9A0C-0305E82C3301
var searchId = guidGen.generate("v4");
pendingSearch.add({"id":searchId,"search":result});
response.writeAndEnd(searchId ,200,"text/json");
}
//Search is ran asynchronously
search.perform(postData.searchText,callbackSearch);
break;
case "/search/results":
//Get search result in pending searchs
searchResult = pendingSearch.find({"id":postData.searchId});
//Merge search result in a html "canvas file
pageSearchResult = contentProvider.merge("search_result_canvas.html",searchResult );
//Remove pending search
pendingSearch.remove({"id":postData.searchId});
//Send the http response
response.writeAndEnd(pageSearchResult ,200,"text/html");
break;
}
}
读完这个例子后,很明显这是一个相当复杂的方法。因此,我建议在发送回搜索结果的 ajax 请求和在同一页面中填充 div 容器之间进行选择,或者在用户等待回发的地方进行经典表单发布。 (实际的方式是两者的混合)。
希望对你有帮助。