在Django中如何使用Ajax


在Django中如何使用Ajax

Django实现基本请求是这样的:

1、views.py

def hello(request):
    return HttpResponse('Hello World!')

def home(request):
    return render_to_response('index.html', {'variable': 'world'})

2、index.html

<h1>Hello {{ variable }}, welcome to my awesome site</h1>

3、url

url(r'^hello/', 'myapp.views.hello'),
url(r'^home/', 'myapp.views.home'),

Ajax实现如下:

$.ajax({
    url: '127.0.0.1:8000/hello',
    type: 'get', // This is the default though, you don't actually need to always mention it
    success: function(data) {
        alert(data);
    },
    failure: function(data) {
        alert('Got an error dude');
    }
});