如何让django和jquery .ajax发挥出色 - 不会触发成功

时间:2009-11-19 22:03:16

标签: jquery ajax django

整个晚上都看不到我错过的东西:

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');
          }  
        }); 

    });
});

和django代码:

def parse_text(request):


    return HttpResponse("hello", mimetype="text'/plain")

我无法触发成功方法。使用萤火虫我可以看到django返回“你好”并且状态为200.

我也尝试过更改为json(虽然我真正想要的是返回一个html表)。

在js:

dataType: "json",

在视图中:

return HttpResponse('[{"hello": "hello"}]', mimetype="application'/json")

现在返回[{“hello”:“hello”}]和200状态。

我到底在做什么错误!?

最终工作代码:

$(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;
    });
});

并在视图中:

def parse_text(request):

    html = ''
    text = request.POST['text']

    ... generated some html based on the text ...


    return HttpResponse(html)

2 个答案:

答案 0 :(得分:5)

您的jQuery函数不会阻止表单提交发生。因此,由于Ajax是异步的,因此提交发生在从Ajax请求返回数据之前,并且函数永远不会看到它。

要解决此问题,请确保return false;函数末尾有submit - 即在倒数第二个})之前。

答案 1 :(得分:1)

你的两个mimetype例子都包含一个额外的撇号:mimetype="text'/plain"。这是代码的真实方式吗?