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. ....하지만 작동하지 않습니다 ....

헨릭 안데르손

직면하고있는 문제는 Django 템플릿 컴파일 변수를 업데이트하려고하는데 context_listDjango가 페이지를 처음 방문 할 때 제공하는 HTML을 미리 컴파일했기 때문에 AJAX를 사용하여 마술처럼 발생하지 않습니다.

이 문제를 피할 수는 없지만 문제를 해결할 수 있으며 아래에서 두 가지 방법을 보여 드리겠습니다.

success()검색을 관리하는 jQuery 스크립트 핸들러는 재 컴파일 한 새로 HTML을 가져 오지만 어디에서나 사용하지 않으면 작동하지 않습니다. 이 경우 일부 항목을 console. (이것은 옵션 # 2를 사용하는 곳입니다.)

내가보기에 두 가지 옵션이 있습니다. (많은 코드이므로 구현이 아닌 포인터를 제공하므로 모든 재미를 잃지 않을 것입니다!)

두 가지 모두에 대해 간략히 설명하고 원하는 방식을 결정할 수 있습니다.

  1. $.load()재 컴파일 된 템플릿을 가져 오기 위해 jQuerys 메소드를 사용할 수 있습니다 .
  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

Ajax 응답 후 아이콘이 작동하지 않음

분류에서Dev

PHP 스크립트의 AJAX 응답이 작동하지 않음

분류에서Dev

Ajax 요청이 응답하지 않음

분류에서Dev

중첩 된 Ajax 응답 데이터 액세스가 작동하지 않음

분류에서Dev

Ajax 403 응답 후 jquery .click ()이 작동하지 않습니다.

분류에서Dev

JSON 또는 atom + xml 응답이 작동하지 않음 (PHP) 구문 분석

분류에서Dev

AJAX 응답이 유효한 JSON을 반환하고 콘솔 로그가 정의되지 않음

분류에서Dev

Ajax 데이터 응답 데이터가 경고하지 않음

분류에서Dev

Ajax 비동기 응답이 div에로드되지 않음

분류에서Dev

AJAX 페이지 전환, 응답하지 않음

분류에서Dev

Ajax 응답 데이터의 경우 테이블 분류기 정렬이 작동하지 않음

분류에서Dev

Ajax 기능이 작동하지 않음

분류에서Dev

Ajax 호출이 성공시 응답을 표시하지 않음

분류에서Dev

jQuery AJAX 응답이 PHP를 표시하지 않음

분류에서Dev

AJAX $ .post가 응답 데이터를 표시하지 않음

분류에서Dev

JSON 서비스에 대한 Ajax 호출이 작동하지 않음

분류에서Dev

Ajax 응답이 페이지보기에 나오지 않음

분류에서Dev

PHP에 jQuery Ajax 양식 제출이 서버의 응답으로 작동하지 않음

분류에서Dev

Chart.js-Ajax 응답이 허용되지 않음

분류에서Dev

Ajax 응답 후 이벤트가 트리거되지 않음 Jquery

분류에서Dev

Ajax 응답이 JS에 표시되지 않음

분류에서Dev

Ajax 응답이 JS에 표시되지 않음

분류에서Dev

AJAX 응답이 JQuery와 함께 추가되지 않음

분류에서Dev

Facebook Oembed 응답이 Json을 반환하지 않음

분류에서Dev

PHP 버전 5.3.24에서 JSON 응답이 작동하지 않습니다.

분류에서Dev

PHP 스크립트의 JSON 응답이 작동하지 않습니다.

분류에서Dev

IE에서 jQuery Ajax 호출이 작동하지 않음, JSON이 통과하지 못함

분류에서Dev

Angular가 Ajax 응답에서 작동하지 않습니다.

분류에서Dev

IE11에서 작동하지 않는 jQuery Ajax 응답

Related 관련 기사

  1. 1

    Ajax 응답 후 아이콘이 작동하지 않음

  2. 2

    PHP 스크립트의 AJAX 응답이 작동하지 않음

  3. 3

    Ajax 요청이 응답하지 않음

  4. 4

    중첩 된 Ajax 응답 데이터 액세스가 작동하지 않음

  5. 5

    Ajax 403 응답 후 jquery .click ()이 작동하지 않습니다.

  6. 6

    JSON 또는 atom + xml 응답이 작동하지 않음 (PHP) 구문 분석

  7. 7

    AJAX 응답이 유효한 JSON을 반환하고 콘솔 로그가 정의되지 않음

  8. 8

    Ajax 데이터 응답 데이터가 경고하지 않음

  9. 9

    Ajax 비동기 응답이 div에로드되지 않음

  10. 10

    AJAX 페이지 전환, 응답하지 않음

  11. 11

    Ajax 응답 데이터의 경우 테이블 분류기 정렬이 작동하지 않음

  12. 12

    Ajax 기능이 작동하지 않음

  13. 13

    Ajax 호출이 성공시 응답을 표시하지 않음

  14. 14

    jQuery AJAX 응답이 PHP를 표시하지 않음

  15. 15

    AJAX $ .post가 응답 데이터를 표시하지 않음

  16. 16

    JSON 서비스에 대한 Ajax 호출이 작동하지 않음

  17. 17

    Ajax 응답이 페이지보기에 나오지 않음

  18. 18

    PHP에 jQuery Ajax 양식 제출이 서버의 응답으로 작동하지 않음

  19. 19

    Chart.js-Ajax 응답이 허용되지 않음

  20. 20

    Ajax 응답 후 이벤트가 트리거되지 않음 Jquery

  21. 21

    Ajax 응답이 JS에 표시되지 않음

  22. 22

    Ajax 응답이 JS에 표시되지 않음

  23. 23

    AJAX 응답이 JQuery와 함께 추가되지 않음

  24. 24

    Facebook Oembed 응답이 Json을 반환하지 않음

  25. 25

    PHP 버전 5.3.24에서 JSON 응답이 작동하지 않습니다.

  26. 26

    PHP 스크립트의 JSON 응답이 작동하지 않습니다.

  27. 27

    IE에서 jQuery Ajax 호출이 작동하지 않음, JSON이 통과하지 못함

  28. 28

    Angular가 Ajax 응답에서 작동하지 않습니다.

  29. 29

    IE11에서 작동하지 않는 jQuery Ajax 응답

뜨겁다태그

보관