2014-01-15 265 views
0

我想實現一個簡單的代碼測試服務器。客戶將在網頁上提交他們的代碼,我們將運行兩個測試用例(可能需要幾分鐘),我們會發布結果。該頁面將很簡單,提交表單和輸出框。Django,更新頁面的一部分

我的問題是更新輸出框。我正在尋找最簡單的方式來實現輸出框,以便我們在運行不同的測試用例時顯示結果。

我試着用google搜索解決方案,並且發現了一些像socket.io但我的經驗與ajax和socket.io甚至js是非常有限的,所以我正在尋找最簡單的方法來做到這一點。

+1

聽起來像基本的AJAX給我。您獲取結果並使用javascript更新輸出框。 – keyser

+0

我知道它應該是基本的。你可以指點我一些文檔或代碼片段嗎? – Kiarash

回答

1

如果你正在尋找的代碼來自動更新一HTML中的字段是您可以使用的代碼。 JavaScript中的setInterval調度get_log視圖,以便get_log_from_disk方法的結果每1秒鐘被拉動一次。

urls.py

url(r'^get_log/$', 'myapp.views.get_log', name='get_log'), 
    url(r'^submit/$', 'myapp.views.submit', name='submit'), 

views.py

def submit(request): 
    ## Handle POST 
    ## Your code comes here 
    return render(request, 'submit.html', {}) 

def get_log_from_disk(): 
    ## Your code comes here 
    return "Test 1 OK; Test 2 OK" 

def get_log(request): 
    results = get_log_from_disk() 
    return HttpResponse(results) 

在submit.html添加

<head> 
    <script src="http://code.jquery.com/jquery-latest.min.js"></script> 
</head> 

<body> 
[<div id="output_box"></div>] 

<script> 
$(document).ready(function() { 
    $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh 
    var my_refresh = setInterval(function() { 
    $('#output_box').load('/get_log/'); 
    }, 1000); // the "1000" 
}); 

</script> 
</body> 

您可以修改「$( '#output_box')。負載( '/ get_log /');」用於測試的請求狀態,當「204無內容」返回你可以刪除功能(clearInterval(my_refresh);)

看到Stop setInterval call in JavaScript

修改get_log視圖返回「204無內容」時,有沒有更多內容要發送。

在這裏,我已經上傳工作版本

https://github.com/lukaszszajkowski/Django-jQuery-Example-update-part-of-page/tree/master

一些閱讀

Auto-refreshing div with jQuery - setTimeout or another method?

+0

這個工作。但它怎麼會更智能..在提交表單之前不ping服務器,服務器發送最後一條消息後沒有ping? – Kiarash

+1

看到我的實現https://github.com/lukaszszajkowski/Django-jQuery-Example-update-part-of-page/tree/master – fragles

+0

順便說一句。我沒有把你的邏輯放在單獨的「結果」視圖和你的「處理文章」評論裏面。除非用戶提交smth,否則不需要結果網址,否則結果網址將無法工作。 – Kiarash

1

這可能是你在找什麼:

var ajaxForm = function() { 
    $.ajax({ 
    type: 'POST', 
    contentType: 'application/json', 
    dataType: 'json', 
    url: '/path/to/django/controller', 
    // The data sent to the Django view in JSON format 
    data: JSON.stringify({ 
     formField: $('#body').val() 
    }), 
    success: function (data) { 
     $('#output-box').html(data); 
    } 
    }); 
} 

$('#form').on('submit', function (e) { 
    e.preventDefault(); 
    ajaxForm(); 
}); 

一個Django控制器的實現可以是這樣的:

import json 
from django.http import HttpResponse 

def ajax_view(request): 
    if request.method == 'POST': 
     request_data = json.load(request.raw_post_data) 
     # do something 
     response_data = {} 
     response_data['result'] = 'Failed' 
     response_data['message'] = 'Your test not ended well' 
     return HttpResponse(
      json.dumps(response_data), 
      content_type='application/json' 
     ) 
+0

謝謝。但是有了這個,我怎麼能在完成後發佈每個測試用例的結果呢?我的意思是我想多次更新輸出框 – Kiarash