Ajax JSON响应不起作用
Ajax JSON response not working
我正试图从Django应用程序中获取JSON响应,但响应不起作用:
这是我的看法。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)
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 HttpResponse(template, json.dumps(context), context_instance=RequestContext(request),
content_type="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,status){
alert("Data: " + context + "Status: " + status);
},
error: function( error ){
alert( error );
},
contentType: "application/json; charset=utf-8",
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
。。。。但它不起作用。。。。
您面临的问题是,您正试图更新一个名为context_list
的Django模板编译变量。使用AJAX不会神奇地实现这一点,因为Django已经预先编译了您最初访问页面时提供的HTML。
你无法绕过这一点,但你可以绕过它,下面我将向你展示两种方法。
管理搜索的jQuery脚本中的success()
处理程序会得到重新编译的新HTML,但您没有在任何地方使用它,因此它不起作用。在这种情况下,您只是将一些内容注销到console
。(这将是你使用选项#2的地方。)
在我看来,你有两个选择。(这是很多代码,所以我会给你指针,而不是实现,不会剥夺你所有的乐趣!)
我会把两者都快速分析一下,然后你就可以决定要走哪条路了。
- 您可以使用jQuerys
$.load()
方法来获取重新编译的模板 - 您可以使用
$.getJSON()
获得对象,然后相应地更新HTML
第一个选项-$.load()
#Django
def search_view(keyword, request):
search_result = SearchModel.objects.filter(some_field=keyword)
t = loader.get_template("some_result_template.html")
c = Context({'search_results':search_result})
return render(t.render(c))
#jQuery
$("#result").load("url_to_your_search", { 'keyword': 'search_me' } );
第二个选项-$.getJSON()
#Django
from django.core import serializers
def search_view(keyword, request):
search_result = SearchModel.objects.filter(some_field=keyword)
json_data = serializers.serialize('json', search_result)
return HttpResponse(json_data, mimetype='application/json')
#jQuery
$.getJSON('url_to_your_search_view', { keyword: "search_me" }, function(json_data) {
var items = [];
$.each(json_data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
现在,JSON代码是直接从文档中获取的,所以您必须对其进行修改,但您已经获得了工作所需的要点。
相关文章:
- 我的响应菜单在移动版中不起作用
- Ajax:Ajax响应中的链接不起作用
- 带有 AJAX 响应或 AJAX 响应的 IF 条件.响应.Text 不起作用
- 如何让Webworker真正响应,以及为什么setTimeout()不起作用
- 在表中显示ajax响应不起作用
- jquery在调整大小时响应不起作用
- angularjs不起作用的Json响应
- 响应式导航栏不起作用,品牌变得一团糟
- jquery.click()在Ajax 403响应后不起作用
- 单击事件在响应菜单中不起作用
- 移动响应表单不起作用
- $.ajax、$.post 或 $.get 不起作用,无法使用响应
- 返回了JS对象,但响应文本不起作用
- 响应式 jQuery 不起作用:单击宽度低于 768px 并将鼠标悬停在 768px 上方
- 响应式幻灯片.js插件在IE中不起作用
- ajax 响应包括 image,onClick 事件对图像不起作用 jQuery
- jQuery 自定义内容滚动器在引导表响应式上不起作用
- 响应式语音在 Safari 中不起作用
- jQuery AJAX 调用在 Firefox 中有效,但在 IE 中不起作用 - 返回有效响应
- FB.登录响应会话不起作用