At this all evening and can't see what I'm missing:
JS:
$(document).ready(function() {
$("#form").submit(function () {
var txt = $('textarea[name=text]').val();
$.ajax({
type: "POST",
url: "/parse_text/",
data: {"text": txt},
dataType: "text",
success: function(h) {
alert('ok');
},
error: function() {
alert('failed');
}
});
});
});
And the django code:
def parse_text(request):
return HttpResponse("hello", mimetype="text'/plain")
I can't get it to trigger the success method. Using firebug I can see that django is return "hello" and a status of 200.
I also tried changing to json (though what I really want is to return an html table).
In js:
dataType: 开发者_运维问答"json",
In view:
return HttpResponse('[{"hello": "hello"}]', mimetype="application'/json")
Now return [{"hello": "hello"}] and 200 status.
What on earth am I doing wrong!?
Final working code:
$(document).ready(function() {
$("#form").submit(function () {
var txt = $('textarea[name=text]').val();
$.ajax({
type: "POST",
url: "/parse_text/",
data: {text : txt},
success: function(html) {
$("#actions").html(html);
},
error: function() {
alert("fail");
}
});
return false;
});
});
and in the view:
def parse_text(request):
html = ''
text = request.POST['text']
... generated some html based on the text ...
return HttpResponse(html)
Your jQuery function doesn't prevent the form submit from taking place. So, since Ajax is asynchronous, the submit happens before the data is returned from the Ajax request, and the function never sees it.
To fix this, make sure you have return false;
at the end of the submit
function - ie before the second-from-last })
.
Both of your examples of mimetype include an extra apostrophe: mimetype="text'/plain"
. Is that the way the code really is?
精彩评论