用ajax调用Django生产问题

时间:2012-08-25 13:24:22

标签: jquery ajax django

我第一次将代码从我的开发机器转移到生产中,在我的机器上运行™正在打破现场服务器。当我从Game中检索gamedb game.players[0]实例current_player game {}时,None http://example.com/current_player/47dd98e9c6aa06ab646d39e516ce54d6db70c2bb/ ["Eve", "e4a70a8e99a4efdfd9331d180cd51798b2291a46"] url(r'^start/$', 'briscola.views.play') url(r'^current_player/([a-z0-9]{40})/$', 'briscola.views.current_player') }。但奇怪的是,如果我拿走ajax url并将其粘贴到浏览器中,则视图会正确返回它应该的json。所以请致电以下人员:

function currentPlayer(game_uid) {

  $.ajax({
    type: 'GET',
    url: '/current_player/' + game_uid + '/',
    success: function(play_data) {

      var player_name = play_data[0];
      console.log('current player ' + player_name);

    }

  });
}

提供以下正确输出:

def start(request):

    p1 = Player('Eve')
    p2 = Player('Adam')

    game = Game([p1, p2])
    gamesdb.set(game.uid, game)

    players = game.players

    output = dict(players=players)

    return render_to_response('index.html', output)

@csrf_exempt
def current_player(request, game_uid):

    game = gamesdb.get(game_uid)

    current_player = game.players[0] 
    play_data = simplejson.dumps([current_player.name, current_player.uid])

    return HttpResponse(play_data, mimetype='application/json')    

我怀疑我设置ajax调用的方式有问题,但无法发现任何错误。

这是我的整个电话堆栈:

urls.py

{{1}}

game.js

{{1}}

views.py

{{1}}

1 个答案:

答案 0 :(得分:1)

您需要传递给$.ajax其他参数:dataType: "json"。或者为$.getJSON使用$.ajax包装,为您准备必要的参数。