2012-12-20 25 views
0

這對我來說是足夠的dajaxice。現在我試圖用jQuery來摧毀我的大腦。Django jQuery Ajax。我得到的迴應,但它不插入在HTML

此前,我在做$.get,一切正常。現在,當我嘗試它$.ajax(獲取) 這是我有:

urls.py

from django.conf.urls import patterns, include, url 
from BitProject.views import index_page,xhr_test 


urlpatterns = patterns('', 
    (r'^$', index_page), 
    url(r'^ajaxrequest/$', xhr_test, name='ajaxurl'), 
) 

views.py

from django.http import HttpResponse 
from django.shortcuts import render_to_response 
from django.utils import simplejson 


def index_page(request): 
    return render_to_response ('template_1.html') 

def xhr_test(request): 
    if request.is_ajax(): 
     message = "Hello AJAX" 
    else: 
     message = "Hello" 
    return HttpResponse(simplejson.dumps(message), mimetype="applicaton/json") 

template_1.html

<html> 
    <head> 

    {% load staticfiles %} 
    <link rel="stylesheet" href="{% static "css/style_2.css" %}" type="text/css"> 
    <script src="{% static "js/jquery_v183.js" %}"></script> 

    <script> 
     $(document).ready(function(){ 
      $('#picture_1').click(function(){ 
       $.ajax({ 
        url:"/BitProject/ajaxrequest/", 
        type: 'GET', 
        success: function(data){ 
         $('#someEl_2').html(data) 
        }, 
        dataType: JSON 
       }); 
      }); 
     }); 


    </script> 
    </head> 

    <body> 
     <img src="{% static "images/sunny.png" %}" id="picture_1" magrin='10px'/> 
     <div id="someEl_2">First Text</div> 
     </div> 
    <body> 
</html> 

我正在使用chrome。我在控制檯中看到我有迴應 - 在回覆標籤中 - Hello AJAX。但頁面上沒有任何反應。我的問題在哪裏?

+0

是的,我知道CSRF (和鋼不能使用它),但在我的實驗與$ .get所有作品沒有任何csrf工具 – kvadrat

+1

'JSON'應該是''json''(一個字符串)。給你的$ .ajax添加一個錯誤回調,以便你可以看到是什麼導致它失敗。當它工作時,你應該期望看到頁面中的[object Object]。 –

+0

當你在'success'方法中做'console.log('data')時會發生什麼?你可能想試試'success:function(status,data,xhr)'而不是'success:function(data)'。此外,只需使'JSON' - >''json'' – karthikr

回答

1

你可以把dataType在引號之間的javascript,更改:

dataType: JSON 

dataType: 'json' 

是什麼,當你直接訪問/BitProject/ajaxrequest/您的瀏覽器呢?

+0

它是行之有效的!謝啦 – kvadrat

0

您在view's的代碼中也有輸入錯誤。替換:

MIME類型= 「一個應用/JSON」

爲:

MIME類型= 「應用/JSON」

相關問題