簡體   English   中英

使用jQuery .post方法將數據發送到Django服務器但出現錯誤500?

[英]Using jQuery .post method to send data to Django server but getting error 500?

我是Django的新手,並且正在制作一款具有10x10木板的游戲,如果單擊該木板,它將被標記為“ X”。 在我的一個模型中,我有一個屬性,用於存儲每個板單元的值,並且默認情況下將其設置為空白。 我可以用jquery標記董事會。 但是,我想將數據發送到服務器端以使其知道我單擊的單元格已標記。 這樣,當我退出游戲並稍后重新訪問時,游戲板將顯示帶有“ X”的標記單元。

這是我的HTML頁面中嵌入的我的jquery代碼:

<script>
$(document).ready(function(){ 
    $('.target_cell').click(function(){ 
        if ($(this).text() != "X" && $(this).text() != "H"){
            $(this).text("X");
            var spot = $(this).attr('name'); //Cell index number like in an array
            $.post("/play_game/{{game.id}}/", spot);
        }
        else{
            alert("Spot already taken!");
        }
    });
});
</script>

這是我的jquery .post方法正在訪問的視圖代碼:

def play_game(request, game_id):
    game = fetch_game(request.user, game_id)
    if request.method == 'POST':
        spot = request.POST['spot']
        game.creator_target_board[int(spot)] = "X"
    variables = RequestContext(request, {
        'game': game,
        'set_board': game.creator_ship_board,
        'target_board': game.creator_target_board
    })
    return render_to_response('battleship/play_game.html', variables)

我目前在視圖上使用csrf_exempt只是為了進行測試。 當我單擊板單元時,它會被標記為“ X”,但是我的服務器日志顯示500錯誤。 有想法該怎么解決這個嗎? 提前致謝!

您的urls.py是什么樣的?

我建議通過執行以下操作使用ajax而不是post:

在urls.py中添加:

url(r'^target_spot/(?P<game_id>\d+)/(?P<spot>\d+)/$', target_spot, name='target_spot'),

在您的JavaScript通話中:

$.ajax("/target_spot/{{game.id}}/" + spot);

在您的視圖中添加:

def target_spot(request, game_id, spot):
    if request.is_ajax():
        game = fetch_game(request.user, game_id)
        game.creator_target_board[int(spot)] = "X"

這種方法的優點是您可以分離邏輯,使代碼更整潔,並且代碼運行更快,因為服務器不會在每次發布請求時都傳遞頁面

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM