2015-01-26 77 views
0

好吧,我正在一个网站上工作,我需要一种方法将分数保存到数据库。我从iFrame获得分数,但我不知道如何将它传递给Django视图以将其保存到数据库。 这是我使用来获取分数的模板:将变量从模板传递到查看

{% block content %} 
<script> 
    /* global $ */ 
    $(document).ready(function() { 
    'use strict'; 
    $(window).on('message', function(evt) { 
     //Note that messages from all origins are accepted 
     //Get data from sent message 
     var msg = evt.originalEvent.data; 
     if(msg.messageType == "SCORE") 
     { 
     msg.score 
     ??? 
     } 
    }); 
    }); 
</script> 
<iframe id="game_iframe" src={{gameurl}}></iframe> 
{% endblock %} 

我将使用某种模式的最终拯救分数,但现在我只是路过这个变量从模板的观点感兴趣。

+1

这不是一个真正的Django模板问题,它更像是一个我怀疑的JS问题。一个可能的答案是启动一个调用Django视图的Ajax POST请求。但是也许你可以多说一些你已经尝试过的东西,哪些部分会让你感到困难? – dylrei 2015-01-26 19:49:55

回答

1

你需要做的是设置一个Ajax请求&在django视图中处理得分等。

读一读这&它应该给你你需要的一切; http://www.tangowithdjango.com/book/chapters/ajax.html

你可能最终得到JS有点像这样;

{% block content %} 
<script> 
    /* global $ */ 
    $(document).ready(function() { 
    'use strict'; 
    $(window).on('message', function(evt) { 
     //Note that messages from all origins are accepted 
     //Get data from sent message 
     var msg = evt.originalEvent.data; 
     if(msg.messageType == "SCORE") 
     { 
     $.get('/game/save_score/', {score: msg.score}, function(data){ 
      $('#score').html(data); 
     }); 
     } 
    }); 
    }); 
</script> 
<iframe id="game_iframe" src={{gameurl}}></iframe> 
{% endblock %} 

和一个视图;

def save_score(request): 
    context = RequestContext(request) 
    score = None 
    if request.method == 'GET': 
     score = request.GET['score'] 

    # Do whatever you need to save the score. 

    return HttpResponse(score) 
+0

非常感谢!我尝试在链接中提到的url中加入url(r'^/game/score/$,save_score),但是我从中得到了404.然后我尝试了url(r'^/game/score /( ()\ d +(?:\。\ d +))/ $',save_score)给出了500.我尝试在响应函数中添加alert以查看它是否可用,但它从未弹出过。 (分数:msg.score),函数(data){ //$('#score').html(data); \t \t alert(“woho”); }); – 2015-01-27 08:35:54

+0

好的,我在URL映射中有一个不需要的地方,但是在尝试提交分数时我仍然收到错误500。 “GET/game/save_score /?score = 1 HTTP/1.1”500 10255 – 2015-01-27 10:38:09

+0

@OuTsei您可以使用视图,URL模式和500追踪来更新您的问题吗? – 2015-01-27 10:48:40