问题
I have a django template which extends the base template that has code to load jquery in it. This template has a simple text box and I wanted to fetch the object through ajax.
{% extends 'base.html' %}
{% block content %}
<form id="ajaxform">
<input type="text" name="first_name" id="name" />
<input type="submit" value="Submit" />
</form>
<div id="dataDiv">
</div>
<script>
$('#ajaxform').submit(function(){
console.log('Form submitted');
$.get('{% url get_ajax_data %}', $(this).serialize(),function(data){
$('#dataDiv').text(data);
})
return false;
});
</script>
{% endblock %}
In this template, I tried to make ajax call to the get_ajax_data url and in the corresponding view I simply returned text as return HttpResponse('Ajax respose')
. But this does not seem to work and the form gets submitted while I have returned false. I am not sure where I missed.
回答1:
Till was on to the answer, Common practice is to initialize the submit()
handler. This is done by setting it when the page is ready. Currently you have it to submit the form the regular way, it's not even registering with your javascript. To fix it you could write:
$(document).ready(function() {
$('#ajax_form').submit(fun // the rest of your code here.
});
回答2:
jQuery event handlers fail silently if there's an error in them. Check for the obvious things like missing semicolons, etc. Make sure everything is valid in the event handler and it should work.
来源:https://stackoverflow.com/questions/8744685/ajax-call-from-django-template