Django - AJAX POST导致管道损坏

时间:2016-04-13 05:17:03

标签: jquery python ajax django

我知道断管是因为冲突请求造成的,所以POST没有时间处理。

我发送这两个请求:

  1. Ajax Post
  2. 重定向到/message.html
  3. 所以event.preventDefault()可能会解决这个问题。但是,当我添加preventDefault()选项时,我根本没有收到POST请求。 并且添加超时将是一个非常糟糕的解决方案,因为它会在每次请求时停止。

    我得到的错误是:

    [13/Apr/2016 10:36:38]"POST /secreturl HTTP/1.1" 500 12202
    - Broken pipe from ('127.0.0.1', 51133)
    

    我的html页面:

    <!DOCTYPE html>
    {% load staticfiles %}
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link href='https://fonts.googleapis.com/css?family=Merriweather+Sans' rel='stylesheet' type= 'text/css'>
        <link href="{% static 'css/main.css' %}" type="text/css" rel="stylesheet">
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">
    </head>
    
    <script type = "text/javascript" 
      src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    
    <script type="text/javascript">
        function clicked(){
            //alert("Coming inside clicked!");
            ValidateEmail();
        }
        function ValidateEmail(){  
            //ValidateEmail.preventDefault();
            if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById("validate-text").value)){
                //alert("correct email!");  
                // do a post request to insert into db
                var email = document.getElementById("validate-text").value
                var datz = {
                    "email" : email,
                    csrfmiddlewaretoken:'{{csrf_token}}'
                }
    
                $.ajax(
                {
                    url: '/secreturl',
                    type: "POST",
                    data: datz,
                    success: function (result) {
                        //alert('startline posted');
                    },
                    error: function (jqXhr, textStatus, errorThrown) {
                     //alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
                    }
                });
                return (true);
    
            }else{  
                alert("You have entered an invalid email address!");  
                return (false);
            } 
        } 
    </script>
    
    <body>
        <div class="site-wrapper">
            <div class="site-wrapper-inner">
                <div class="cover-container">
                    <div class="center-block col-md-7">
                        <div class="row">
                            <div class="col-md-12 padding0">
                                <img src="{% static 'img/CowsCrop.png' %}" width="90%">
                                <div class="image-caption">Her 'Achhe din' are definitely here. What about yours?</div>
                                <img src="{% static 'img/mobile.png' %}" width="70%" class="padding2">
                                <div class="form-group">
                                    <div class="input-group col-md-10 col-md-offset-1">
                                        <input type="text" class="form-control flat-form" name="validate-text" id="validate-text" placeholder="Leave your e-mail & be the 1st one to know when the awesomeness is out!" required>
                                        <span class="input-group-addon danger flat-form button-color">
                                            <!-- <a href="message.html" onclick="clicked()">I WANT IT!</a> -->
                                            <a href="/message" onclick="return ValidateEmail();">Want It!</a>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="pull-right padding1">
                                <img src="{% static 'img/facebook.png' %}" width="32px" height="32px">
                                <img src="{% static 'img/twitter.png' %}" width="32px" height="32px">
                                <img src="{% static 'img/instagram.png' %}" width="32px" height="32px">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
        <script   src="https://code.jquery.com/jquery-2.2.2.min.js"   integrity="sha256-36cp2Co+/62rEAAYHLmRCPIych47CvdM+uTBJwSzWjI="   crossorigin="anonymous"></script>
        <script type="application/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </html>
    

    还有一件事我想添加,我也无法发送csrf_token,因为我要去JSON.stringify(数据)django无法提取csrf_token它,我也没有使用任何形式,因此无法使用:

    <form></form> {% csrf_token %}
    

    服务器端:

    //views.py
    def home(request):
        print "Request has been received"
        print request
        context = {
            'MEDIA_ROOT' : "//home//mayur//Documents//Gigit//Gigit//Gigit//static//images//",
            'MEDIA_URL' : 'http://localhost:8000/static/',
        }
        return render(request, "index2.html", context)
    
    def test(request):
        print "POST works"
        #return render(request,"", {})
    
    def message(request):
        print " message request received"
        return render(request, "message.html", {})
    
    def insertQuery(request):
        print "Insert query received"
        # resp = json.loads(request)
        # print resp
        print request
    
    //models.py
    class visitors(models.Model):
    id = models.AutoField(primary_key=True)
    email = models.CharField(max_length = 50)
    quesId = models.CharField(max_length = 2)
    answer = models.CharField(max_length = 200)
    notify = models.BooleanField(default = True)
    regTime = models.DateTimeField(auto_now = True)
    
    //urls.py
    urlpatterns = [
    
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'questionAnswer.views.home'),
    url(r'^test/', 'questionAnswer.views.test'),
    url(r'^message', 'questionAnswer.views.message'),
    url(r'^secreturl', 'questionAnswer.views.insertQuery'),
    
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

1 个答案:

答案 0 :(得分:0)

将重定向代码放在成功函数

success: function (result) {
    //alert('startline posted');
},
AJAX POST方法的

解决了我面临的类似问题。