Reputation: 482
Ok, I'm working on a website and I need a way to save score to database. I get the score from an iFrame, but I dont know how to pass it to a Django view to save it to the DB. This is the template I'm using to get the score:
{% 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 %}
I will be using some sort of model to save the score eventually but now I'm just interested passing this variable from the template to the view.
Upvotes: 0
Views: 1610
Reputation: 12869
What you need to do is setup an Ajax request & handle the score etc in a django view.
Take a read of this & it should give you everything you need; http://www.tangowithdjango.com/book/chapters/ajax.html
You'll probably end up with JS a bit like this;
{% 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 %}
And a view;
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)
Upvotes: 1