2015-01-04 41 views
1

我正在用Django制作一个网站,它使用AJAX将一些信息发布到后端。这种情况下的信息是用户键入的总时间(从他开始输入的时间)到他按下提交的时间。但是,出于某种原因,我在命令提示符下不断收到错误。浏览器控制台只有0:,这表示POST中有错误。我在处理帖子(passage_result)的视图中有一堆打印语句来帮助找到错误,并且它似乎与return HttpResponse(json.dumps(response_data), content_type="text/html")行有关,因为每一个打印语句都会返回预期的答案。AJAX POST上的Django [WinError 10053]

以下是错误:

[04/Jan/2015 10:30:40] "POST /typer/passage_result/ HTTP/1.1" 200 140 
Traceback (most recent call last): 
    File "C:\Python34\lib\wsgiref\handlers.py", line 138, in run 
    self.finish_response() 
    File "C:\Python34\lib\wsgiref\handlers.py", line 180, in finish_response 
    self.write(data) 
    File "C:\Python34\lib\wsgiref\handlers.py", line 274, in write 
    self.send_headers() 
    File "C:\Python34\lib\wsgiref\handlers.py", line 332, in send_headers 
    self.send_preamble() 
    File "C:\Python34\lib\wsgiref\handlers.py", line 255, in send_preamble 
    ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') 
    File "C:\Python34\lib\wsgiref\handlers.py", line 453, in _write 
    self.stdout.write(data) 
    File "C:\Python34\lib\socket.py", line 391, in write 
    return self._sock.send(b) 
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine 
[04/Jan/2015 10:30:40] "POST /typer/passage_result/ HTTP/1.1" 500 59 
---------------------------------------- 
Exception happened during processing of request from ('127.0.0.1', 58785) 
Traceback (most recent call last): 
    File "C:\Python34\lib\wsgiref\handlers.py", line 138, in run 
    self.finish_response() 
    File "C:\Python34\lib\wsgiref\handlers.py", line 180, in finish_response 
    self.write(data) 
    File "C:\Python34\lib\wsgiref\handlers.py", line 274, in write 
    self.send_headers() 
    File "C:\Python34\lib\wsgiref\handlers.py", line 332, in send_headers 
    self.send_preamble() 
    File "C:\Python34\lib\wsgiref\handlers.py", line 255, in send_preamble 
    ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') 
    File "C:\Python34\lib\wsgiref\handlers.py", line 453, in _write 
    self.stdout.write(data) 
    File "C:\Python34\lib\socket.py", line 391, in write 
    return self._sock.send(b) 
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "C:\Python34\lib\wsgiref\handlers.py", line 141, in run 
    self.handle_error() 
    File "C:\Python34\lib\wsgiref\handlers.py", line 368, in handle_error 
    self.finish_response() 
    File "C:\Python34\lib\wsgiref\handlers.py", line 180, in finish_response 
    self.write(data) 
    File "C:\Python34\lib\wsgiref\handlers.py", line 274, in write 
    self.send_headers() 
    File "C:\Python34\lib\wsgiref\handlers.py", line 331, in send_headers 
    if not self.origin_server or self.client_is_modern(): 
    File "C:\Python34\lib\wsgiref\handlers.py", line 344, in client_is_modern 
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' 
TypeError: 'NoneType' object is not subscriptable 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "C:\Python34\lib\socketserver.py", line 613, in process_request_thread 
    self.finish_request(request, client_address) 
    File "C:\Python34\lib\socketserver.py", line 344, in finish_request 
    self.RequestHandlerClass(request, client_address, self) 
    File "C:\Python34\lib\site-packages\django\core\servers\basehttp.py", line 129 
, in __init__ 
    super(WSGIRequestHandler, self).__init__(*args, **kwargs) 
    File "C:\Python34\lib\socketserver.py", line 669, in __init__ 
    self.handle() 
    File "C:\Python34\lib\wsgiref\simple_server.py", line 133, in handle 
    handler.run(self.server.get_app()) 
    File "C:\Python34\lib\wsgiref\handlers.py", line 144, in run 
    self.close() 
    File "C:\Python34\lib\wsgiref\simple_server.py", line 35, in close 
    self.status.split(' ',1)[0], self.bytes_sent 
AttributeError: 'NoneType' object has no attribute 'split' 
---------------------------------------- 

这里是passage_result观点:

@csrf_exempt 
def passage_result(request): 
    if request.method == 'POST': 
     # Get all of the information needed 
     user_passage = request.POST.get('user_passage') 
     total_time = request.POST.get('time_taken') 
     current_passage = request.POST.get('original_passage') 
     creation_date = request.POST.get('creation_time') 
     user = request.user 
     original_passage = Passage.objects.get(name=current_passage, user=user) 

     print("THIS IS THE TOTAL TIME " + str(total_time)) 

     # Measure word length and character length so I can measure accuracy/wpm 
     user_split = re.findall(r'((?:(?<=^\s)\s*)?\S+\s*(?=\s\S|$))', user_passage) 
     user_wlength = len(user_split) 
     user_clength = len(user_passage) 

     # Compare both strings against one another 
     errors, accuracy, error_indices = checkString.checkWord(original_passage.text_body, user_passage) 

     print("Errors: "+ str(errors)) 
     print("Accuracy: " + str(accuracy)) 

     # Round up the numbers, calculate wpm and cpm 
     accuracy = round(accuracy, 4) 
     minutes = float(total_time)/float(60000) 
     wpm = round(float(user_wlength/minutes), 2) 
     cpm = round(float(user_clength/minutes), 2) 

     overall = round((wpm + accuracy)/2, 2) 

     # Create a passage result for this instance, and save it to the database 

     passageResult = PassageResult(user=user, passage=original_passage, creation_date=creation_date, user_passage=user_passage, total_time=total_time, 
            total_words=user_wlength, total_chars=user_clength, errors=errors, accuracy=accuracy, 
            wpm=wpm, cpm=cpm, overall=overall) 
     passageResult.save() 

     # Get the ranking of each passage, and save it. 
     sorted_results = PassageResult.objects.order_by('-overall') 
     for i in range(0, len(sorted_results)-1): 
      sorted_results[i].rank = i + 1 
      sorted_results[i].save() 
      print(sorted_results[i].rank) 

     # Create the response data that will be dumped json style 
     response_data = {} 
     response_data['result'] = 'Passage submitted successfully!' 
     response_data['user_text'] = passageResult.user_passage 
     response_data['total_time'] = passageResult.total_time 
     response_data['author'] = passageResult.user.username 


     return HttpResponse(
      json.dumps(response_data), 
      content_type="text/html" 
     ) 
    else: 
     return HttpResponse(
      json.dumps({"nothing to see": "this isn't happening"}), 
      content_type="text/html" 
     ) 

这里是我的jQuery代码:

//Create a time so we can update it later 
var time = (new Date()).getTime(); 

//function to update the time when the user starts typing 
$('#id_user_passage').on('keyup', function (event) { 
    event.preventDefault(); 
    time = (new Date()).getTime(); 
}); 

// function to get the total time the user typed from when he started to when 
// he clicked the submit button, and POST the information to the backend, 
// along with what he typed and when he submitted it. 
$('#passage_result_form').on('submit', function(event) { 
    event.preventDefault(); 
    var total_time = (new Date()).getTime() - time; 
    var current_time = (new Date()).getTime(); 
    console.log('Time passed : ' + total_time + ' milliseconds'); 
    console.log('form submitted!') 
    $.ajax({ 
     url: "/typer/passage_result/", 
     type: "POST", 
     data: { 'user_passage': $('#id_user_passage').val(), 'original_passage': $("#name").text(), 'time_taken': total_time, 
     'creation_time' : current_time}, 

     success: function (json) { 
      total_time = 0; 
      console.log(json); 
      console.log("success"); 
     }, 

     error: function (xhr, errmsg, err) { 
      $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: " + errmsg + 
       " <a href='#' class='close'>&times;</a></div>"); 
      console.log(xhr.status + ": " + xhr.responseText); 
     } 
    }); 
    location.replace('/typer/result/'); 

}); 

回答

0

我遇到过同样的问题,通过这样做解决它,只需添加“async:false”到ajax