7

基本上我需要类似于http://www.w3schools.com/jquery/jquery_ajax_get_post.asp在 django 中完成的东西。我已经下载了示例并使用 localhost + php 在本地对其进行了测试,并且效果很好,但是无论示例多么简单,我似乎都无法让它在 django 中工作。这基本上是我根据上面链接中的示例所做的,稍作修改

的JavaScript:

<script type="text/javascript">
$(document).ready(function(){
  $("#my_form").submit(function(){
    $.post("",
    {name:"Donald Duck",
     city:"Duckburg"},
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    })
    .fail(function() { alert("error"); });
    return false;
  });
});
</script>

网址:

url(r'^ajax/$', views.ajax_test, name="ajax"),

观点:

def ajax_test(request):
    if request.method == 'POST' and request.is_ajax():
        name = request.POST['name']
        city = request.POST['city']
        message = name + ' lives in ' + city

        return HttpResponse(json.dumps({'message': message})) #tried without the json. Doesn't work either

    return render(request, 'books/ajaxTest.html')

的HTML:

<form id="my_form" action="" method="post" {% if form.is_multipart %}enctype="multipart/form-data"{% endif %}>{% csrf_token %}
<input type="submit" value="Send">
</form>

该表单应该包含一个 django 表单,但由于我什至无法获得基本的工作,那将是毫无意义的。有人提到了 csrf_token 标签,但删除它也不能解决问题。上面示例的输出基本上只产生 alert('error') 而没有别的。我经历了很多例子,但我什至无法让最基本的例子起作用

4

2 回答 2

8

好的..谢谢你的评论..我把一切都整理好了..基本上我只是错过了 {% csrf_token %} 和 csrfmiddlewaretoken:'{{ csrf_token }}'..只是为了那些可能的人的利益阅读这个..新代码看起来像这样

的JavaScript:

<script type="text/javascript">
$(document).ready(function(){

  $("#my_form").submit(function(){
    $.post("",
    {name:"Donald Duck",
     city:"Duckburg",
     csrfmiddlewaretoken:'{{ csrf_token }}'
     },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    })
    .fail(function(xhr) {
        console.log("Error: " + xhr.statusText);
        alert("Error: " + xhr.statusText);
    });
    return false;
  });

});
</script>

的HTML:

<form id="my_form" action="" method="post">{% csrf_token %}
<input type="submit" value="Send">
</form>
于 2013-06-02T16:51:07.630 回答
5

检查此示例:检查此链接

楷模

class Color(models.Model):
    color = models.CharField(max_length=256)

class Auto(models.Model):
    type = models.CharField('auto type', max_length=256)
    colors = models.ManyToManyField(Color) 

from django import forms
from models import Color, Auto

    class AutoForm(forms.Form):
        TYPE_CHOICES = [('', '-- choose a type --'), ] + [(t.type, t.type) for t in Auto.objects.all()]
        COLOR_CHOICES = [(c.color, c.color) for c in Color.objects.all()]
        COLOR_CHOICES.insert(0, ('', '-- choose a vehicle type first --'))

        type = forms.ChoiceField(choices=TYPE_CHOICES, widget=forms.Select(attrs={'onchange':'get_vehicle_color();'}))
        color = forms.ChoiceField(choices=COLOR_CHOICES)
    [Check this article][2] can be helpful

模板

{% extends "base.html" %}
{% block head %}
<script type="text/javascript" src="/site_media/prototype.js"></script>
<script type="text/javascript" src="/site_media/my_ajax_function.js"></script>
{% endblock %}

{% block content %}
    {% if form_was_valid %}
        {# ... show whatever... #}
    {% else %}
        <form action="/auto/reserve/" method="POST">
        <ul>
        {{ form.as_ul}}
        <li><label for="submit">&nbsp;</label>
        <input type="submit" id="submit" name="submit" value="Submit"/></li>
        </ul>
        </form>
    {% endif %}
{% endblock %}

Javascript

function get_vehicle_color(){
    new Ajax.Request('/auto/ajax_purpose_staff/', { 
    method: 'post',
    parameters: $H({'type':$('id_type').getValue()}),
    onSuccess: function(transport) {
        var e = $('id_color')
        if(transport.responseText)
            e.update(transport.responseText)
    }
    }); // end new Ajax.Request
}

网址.py

urlpatterns = patterns('mysite.auto.views',
    (r'^ajax_color_request/$', 'ajax_color_request'),
    # ... everything else...
)


def ajax_color_request(request):
    # Expect an auto 'type' to be passed in via Ajax and POST
    if request.is_ajax() and request.method == 'POST
        auto_type = Auto.objects.filter(type=request.POST.get('type', ''))
        colors = auto_type.colors.all() # get all the colors for this type of auto.
    return render_to_response('auto/ajax_color_request.html', locals())

{% for c in colors %}
    <option value="{{ c.color }}">{{ c.color|title }}</option>
{% endfor %}
于 2013-05-29T12:59:27.313 回答