Ajax JSON响应不起作用

瓦伊卜·贾恩(Vaibhav Jain)

我正在尝试从Django应用程序获取JSON响应,但响应不起作用:

这是我的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)            

            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...。但是它不起作用....

亨里克·安德森(Henrik Andersson)

您面临的问题是,context_list由于Django在您初次访问页面时已经预编译了要提供的HTML ,因此您尝试使用AJAX来更新名为Django模板的已编译变量不会发生神奇的变化。

您不能回避它,但是可以解决它,下面我将向您展示两种实现方法。

success()在jQuery脚本中用于管理搜索的处理程序将获得重新编译的新HTML,但是您不会在任何地方使用它,因此不会起作用。在这种情况下,您只是将一些内容登出到console(这就是您使用选项2的地方。)

我认为您有两个选择。(这是很多代码,因此我将为您提供指针而不是实现,不会剥夺您的所有乐趣!)

我将为您提供两者的简要介绍,然后您可以决定采用哪种方式。

  1. 您可以使用jQuerys$.load()方法来获取重新编译的模板。
  2. 您可以使用$.getJSON()并获取JSON格式的对象,然后相应地更新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代码直接从文档中获取,因此您必须对其进行修改,但是您可以清楚地了解需要什么才能使您的代码工作。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

JQuery Ajax Json响应不起作用

来自分类Dev

Wordpress AJAX不起作用-响应0

来自分类Dev

Ajax响应后图标不起作用

来自分类Dev

Ajax 条件响应不起作用

来自分类Dev

jQuery Ajax调用在IE中不起作用,JSON响应无法通过

来自分类Dev

对带有文件的ajax的响应不起作用

来自分类Dev

在jsp上设置Ajax响应不起作用

来自分类Dev

从ajax响应强制下载xlsx不起作用

来自分类Dev

AJAX从PHP响应更改div内容不起作用

来自分类Dev

嵌套的Ajax响应数据访问不起作用

来自分类Dev

来自PHP脚本的AJAX响应不起作用

来自分类Dev

响应在 ajax 自动完成中不起作用

来自分类Dev

Ajax不起作用

来自分类Dev

Ajax承诺不起作用

来自分类Dev

Ajax形式不起作用

来自分类Dev

Ajax测试不起作用

来自分类Dev

Ajax链接不起作用

来自分类Dev

Ajax的代码不起作用

来自分类Dev

Ajax代码不起作用

来自分类Dev

Ajax更新不起作用

来自分类Dev

Ajax形式不起作用

来自分类Dev

Ajax发布不起作用

来自分类Dev

AJAX方法不起作用

来自分类Dev

Ajax查询不起作用

来自分类Dev

具有AJAX响应或AJAX response.response.Text的IF条件不起作用

来自分类Dev

具有AJAX响应或AJAX response.response.Text的IF条件不起作用

来自分类Dev

通过ajax调用echo json_encode()不起作用

来自分类Dev

对JSON服务的Ajax调用不起作用

来自分类Dev

使用Ajax / Json更新Mysql记录不起作用