我正在尝试根据用户搜索查询更新我的页面。我可以从服务器获取搜索结果,但如何更新contextList
。我还实现了Django无尽的分页,但我如何用新内容重新加载列表
views.py
import json
import traceback
from django.http import HttpResponse
from django.template import Context,loader
from django.template import RequestContext
from django.shortcuts import render_to_response
from eScraperInterfaceApp.eScraperUtils import eScraperUtils
#------------------------------------------------------------------------------
def renderError(message):
"""
This function displays error message
"""
t = loader.get_template("error.html")
c = Context({ 'Message':message})
return HttpResponse(t.render(c))
def index(request,template = 'index.html',
page_template = 'index_page.html' ):
"""
This function handles request for index page
"""
try:
context = {}
contextList = []
utilsOBJ = eScraperUtils()
q = {"size" : 300000,
"query" :{ "match_all" : { "boost" : 1.2 }}}
results = utilsOBJ.search(q)
for i in results['hits']['hits']:
contextDict = i['_source']
contextDict['image_paths'] = json.loads(contextDict['image_paths'])
contextList.append(contextDict)
context.update({'contextList':contextList,'page_template': page_template})
if request.is_ajax(): # override the template and use the 'page' style instead.
template = page_template
return render_to_response(
template, context, context_instance=RequestContext(request) )
except :
return renderError('%s' % (traceback.format_exc()))
def search (request,template = 'index.html',
page_template = 'index_page.html' ):
try:
if request.method == 'POST':
context = {}
contextList = []
keyWord = request.POST['keyWord']
print keyWord
utilsOBJ = eScraperUtils()
results = utilsOBJ.search('productCategory:%(keyWord)s or productSubCategory:%(keyWord)s or productDesc:%(keyWord)s' % {'keyWord' : keyWord})
for i in results['hits']['hits']:
contextDict = i['_source']
contextDict['image_paths'] = json.loads(contextDict['image_paths'])
contextList.append(contextDict)
if request.is_ajax(): # override the template and use the 'page' style instead.
template = page_template
context.update({'contextList':contextList,'page_template': page_template})
return HttpResponse(json.dumps(context), mimetype='application/json')
except :
return renderError('%s' % (traceback.format_exc()))
#------------------------------------------------------------------------------
index.html:
<html>
<head>
<title>Fashion</title>
<link rel="stylesheet" type="text/css" href="static/css/style.css">
</head>
<body>
<form action="">
{% csrf_token %}
<input id="query" type="text" />
<input id="search-submit" type="button" value="Search" />
</form>
<div class="product_container">
<ul class="product_list">
<div class="endless_page_template">
{% include page_template %}
</div>
</ul>
</div>
<div class="product_container">
<ul class="product_list">
<div class="endless_page_template">
{% include page_template %}
</div>
</ul>
</div>
{% block js %}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="static/js/endless_on_scroll.js"></script>
<script src="static/js/endless-pagination.js"></script>
<script>
$.endlessPaginate({paginateOnScroll: true,
endless_on_scroll_margin : 10,
paginateOnScrollChunkSize: 5
});</script>
<script type="text/javascript">
$("#search-submit").click(function() {
// Get the query string from the text field
var query = $("#query").val();
alert(query);
data = { 'csrfmiddlewaretoken': '{{ csrf_token }}', 'keyWord' : query};
// Retrieve a page from the server and insert its contents
// into the selected document.
$.ajax({
type: "POST",
url: '/search/',
data: data,
success: function(context){
var items = [];
var jsonData = JSON.parse(JSON.stringify(context));
console.log(jsonData['contextList']);
$.each(jsonData['contextList'], function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'product_list',
html: items.join('')
}).appendTo('body');
},
error: function( error ){
alert( error );
},
dataType: 'json',
});
});
</script>
{% endblock %}
</body>
</html>
index_page.html:
{% load endless %}
{% paginate 10 contextList %}
{% for item in contextList %}
<li >
<a href="{{ item.productURL }}" ><img src="/images/{{ item.image_paths.0 }}/" height="100" width="100" border='1px solid'/></a>
<br>
<span class="price">
<span class="mrp">MRP : {{ item.productMRP}}</span>
{% if item.productPrice %}<br>
<span class="discounted_price">Offer Price : {{ item.productPrice}}</span>
{%endif%}
</span>
</li>
{% endfor %}
{% show_more "even more" "working" %}
有人可以告诉我如何使用新数据重新加载contextList
....