我希望有人可以提供帮助,因为我多次尝试这种情况并没有取得什么成功。我试图使用django书中的探戈来适应这种情况,并在网上做了许多其他例子,但没有运气。总之...
我目前正在设计一个小型假新闻'有Django的网站,它有一个迷你游戏,向用户显示新闻文章(标题,描述,图片),他们必须投票是否是“事实”。或者'小说'然后告诉他们他们是否正确以及之前有多少人投票赞成该答案。
如果我将所有数据存储在如下的javascript变量中,我的工作完全正常:
var questions = [
["Pope Francis Shocks World, Endorses Donald Trump for President, Releases Statement",
"News outlets around the world are reporting on the news that Pope Francis has made the unprecedented decision to endorse a US presidential candidate. His statement in support of Donald Trump was released from the Vatican this evening: 'I have been hesitant to offer any kind of support for either candidate in the US presidential election but I now feel that to not voice my concern would be a dereliction of my duty as the Holy See...",
"fake", 7, 15, '../../static/images/popetrump.jpg'],
["Trump Offering Free One-Way Tickets to Africa & Mexico for Those Who Wanna Leave America",
"President elect Donald Trump has sensationally offered free one-way tickets to Mexico or Africa for anyone who wants to leave America in the aftermath of his election victory. The extraordinary, and highly controversial, offer was revealed by an aid at a press conference in New York this morning...",
"fake", 13, 17, '../../static/images/TrumpTickets.jpg'],
["Feral pig drinks 18 cans of beer, fights cow and then passes out drunk under tree",
"The swine drank 18 beers on its bender in Port Hedland, Western Australia, according to ABC News. The alcohol also made the pig hungry and was seen looking through rubbish bags for something to eat...",
"true", 8, 19, '../../static/images/pig.jpg'],
["Cinnamon Roll Can Explodes Inside Man's Butt During Shoplifting Incident",
"Las Vegas – Martin Klein, 41 of Las Vegas, was arrested after a shopping lifting incident turned horribly wrong. According to reports, Mr. Klein and his partner, Jerry Weis, had stolen several grocery items from the Las Vegas Walmart...",
"fake", 19, 7, '../../static/images/CinnamonRollMan.jpg'],
["Poll: 38% of Florida voters believe Ted Cruz could be the Zodiac Killer",
"While a 62 percent majority of voters answered 'No' when asked if they believed Cruz was responsible for the string of murders in the early 70s, 10 percent answered 'Yes' and an additional 28 percent said they were unsure...",
"true", 11, 6, '../../static/images/FloridaPoll.jpg'],
["Hamster resurrection: Pet rises from the grave at Easter after being buried in garden",
"Tink the hamster was found ‘cold and lifeless’ in the bottom of her cage and laid to rest by a couple who were looking after her for a friend. But the next day the rodent – who was not dead but hibernating – reappeared as perplexed Les Kilbourne-Smith crushed a pile of old boxes for recycling...",
"true", 15, 9, '../../static/images/hamster.jpg'],
]
我已经能够将所有文章添加到数据库中,但我不确定如何在需要时从数据库中提取数据,并在更多人玩游戏时更新事实和虚构投票的数量。通过在线阅读,我相信我需要使用AJAX来做到这一点,但我诚实地不知道从哪里开始,每次按下一个按钮时显示一篇新文章,更新投票数等。
希望有人能够至少指出我正确的方向,并且我会发布到目前为止我所拥有的所有代码,并认为可能与以下相关。
game.js:
var questions = [
["Pope Francis Shocks World, Endorses Donald Trump for President, Releases Statement",
"News outlets around the world are reporting on the news that Pope Francis has made the unprecedented decision to endorse a US presidential candidate. His statement in support of Donald Trump was released from the Vatican this evening: 'I have been hesitant to offer any kind of support for either candidate in the US presidential election but I now feel that to not voice my concern would be a dereliction of my duty as the Holy See...",
"fake", 7, 15, '../../static/images/popetrump.jpg'],
["Trump Offering Free One-Way Tickets to Africa & Mexico for Those Who Wanna Leave America",
"President elect Donald Trump has sensationally offered free one-way tickets to Mexico or Africa for anyone who wants to leave America in the aftermath of his election victory. The extraordinary, and highly controversial, offer was revealed by an aid at a press conference in New York this morning...",
"fake", 13, 17, '../../static/images/TrumpTickets.jpg'],
["Feral pig drinks 18 cans of beer, fights cow and then passes out drunk under tree",
"The swine drank 18 beers on its bender in Port Hedland, Western Australia, according to ABC News. The alcohol also made the pig hungry and was seen looking through rubbish bags for something to eat...",
"true", 8, 19, '../../static/images/pig.jpg'],
["Cinnamon Roll Can Explodes Inside Man's Butt During Shoplifting Incident",
"Las Vegas – Martin Klein, 41 of Las Vegas, was arrested after a shopping lifting incident turned horribly wrong. According to reports, Mr. Klein and his partner, Jerry Weis, had stolen several grocery items from the Las Vegas Walmart...",
"fake", 19, 7, '../../static/images/CinnamonRollMan.jpg'],
["Poll: 38% of Florida voters believe Ted Cruz could be the Zodiac Killer",
"While a 62 percent majority of voters answered 'No' when asked if they believed Cruz was responsible for the string of murders in the early 70s, 10 percent answered 'Yes' and an additional 28 percent said they were unsure...",
"true", 11, 6, '../../static/images/FloridaPoll.jpg'],
["Hamster resurrection: Pet rises from the grave at Easter after being buried in garden",
"Tink the hamster was found ‘cold and lifeless’ in the bottom of her cage and laid to rest by a couple who were looking after her for a friend. But the next day the rodent – who was not dead but hibernating – reappeared as perplexed Les Kilbourne-Smith crushed a pile of old boxes for recycling...",
"true", 15, 9, '../../static/images/hamster.jpg'],
]
var questionCount = 0;
var correctAnswer = 0;
$(document).ready(function() {
$("#answer").hide();
$("#game_home").hide();
$("#game_title").html(questions[questionCount][0]);
$("#game_description").html(questions[questionCount][1]);
$("#game_picture").attr('src', questions[questionCount][5]);
$("#game_fact").click(function() {
$("#game_picture").hide();
$("#game_fact").prop('disabled', true);
$("#game_fiction").prop('disabled', true);
if(questions[questionCount][2] == "true"){
$("#your_answer").html("Correct! This story is a Fact!");
$("#current_answer_fact").html("Fact: " + (((questions[questionCount][3])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%");
$("#current_answer_fiction").html("Fiction: " + (((questions[questionCount][4])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%");
questions[questionCount][3] = questions[questionCount][3]+1;
correctAnswer += 1;
}
else{
$("#your_answer").html("Incorrect! This story is actually Fiction!");
$("#current_answer_fact").html("Fact: " + (((questions[questionCount][3])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%");
$("#current_answer_fiction").html("Fiction: " + (((questions[questionCount][4])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%");
questions[questionCount][3] = questions[questionCount][3]+1
}
$("#answer").show();
});
$("#game_fiction").click(function() {
$("#game_picture").hide();
$("#game_fact").prop('disabled', true);
$("#game_fiction").prop('disabled', true);
if(questions[questionCount][2] == "fake"){
$("#your_answer").html("Correct! This story is Fiction!");
$("#current_answer_fact").html("Fact: " + (((questions[questionCount][3])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%");
$("#current_answer_fiction").html("Fiction: " + (((questions[questionCount][4])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%");
questions[questionCount][3] = questions[questionCount][4]+1
correctAnswer += 1;
}
else{
$("#your_answer").html("Incorrect! This story is actually a Fact!");
$("#current_answer_fact").html("Fact: " + (((questions[questionCount][3])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%");
$("#current_answer_fiction").html("Fiction: " + (((questions[questionCount][4])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%");
questions[questionCount][3] = questions[questionCount][4]+1
}
$("#answer").show();
});
$("#game_next").click(function() {
questionCount += 1;
if(questionCount == questions.length){
$("#your_answer").html("Thanks for playing!");
$("#current_answer").html("You scored " + correctAnswer + " out of " + questions.length);
$("#game_home").show();
$("#game_fact").hide();
$("#game_fiction").hide();
$("#game_title").hide();
$("#game_description").hide();
$("#game_next").hide();
$("#current_answer_fact").hide();
$("#current_answer_fiction").hide();
$("#game_or").hide();
}
else{
$("#game_picture").attr('src', questions[questionCount][5]);
$("#answer").hide();
$("#game_picture").show();
$("#game_title").html(questions[questionCount][0]);
$("#game_description").html(questions[questionCount][1]);
$("#game_fact").prop('disabled', false);
$("#game_fiction").prop('disabled', false);
}
});
});
人口脚本:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fact_or_fiction.settings')
import django
django.setup()
from factorfiction.models import Page, GameArticle
def populate():
game_articles = [
{"title":"Pope Francis Shocks World, Endorses Donald Trump for President, Releases Statement",
"description":"News outlets around the world are reporting on the news that Pope Francis has made the unprecedented decision to endorse a US presidential candidate. His statement in support of Donald Trump was released from the Vatican this evening: 'I have been hesitant to offer any kind of support for either candidate in the US presidential election but I now feel that to not voice my concern would be a dereliction of my duty as the Holy See...",
"answer":"fake",
"fact": 7,
"fiction": 15,
"picture": "../../static/images/popetrump.jpg"},
{"title":"Trump Offering Free One-Way Tickets to Africa & Mexico for Those Who Wanna Leave America",
"description":"President elect Donald Trump has sensationally offered free one-way tickets to Mexico or Africa for anyone who wants to leave America in the aftermath of his election victory. The extraordinary, and highly controversial, offer was revealed by an aid at a press conference in New York this morning...",
"answer":"fake",
"fact": 13,
"fiction": 17,
"picture": "../../static/images/TrumpTickets.jpg"},
{"title":"Feral pig drinks 18 cans of beer, fights cow and then passes out drunk under tree",
"description":"The swine drank 18 beers on its bender in Port Hedland, Western Australia, according to ABC News. The alcohol also made the pig hungry and was seen looking through rubbish bags for something to eat...",
"answer":"true",
"fact": 8,
"fiction": 19,
"picture": "../../static/images/pig.jpg"},
{"title":"Cinnamon Roll Can Explodes Inside Man's Butt During Shoplifting Incident",
"description":"Las Vegas – Martin Klein, 41 of Las Vegas, was arrested after a shopping lifting incident turned horribly wrong. According to reports, Mr. Klein and his partner, Jerry Weis, had stolen several grocery items from the Las Vegas Walmart...",
"answer":"fake",
"fact": 19,
"fiction": 7,
"picture": "../../static/images/CinnamonRollMan.jpg"},
{"title":"Poll: 38% of Florida voters believe Ted Cruz could be the Zodiac Killer",
"description":"While a 62 percent majority of voters answered 'No' when asked if they believed Cruz was responsible for the string of murders in the early 70s, 10 percent answered 'Yes' and an additional 28 percent said they were unsure...",
"answer":"true",
"fact": 11,
"fiction": 6,
"picture": "../../static/images/FloridaPoll.jpg"},
{"title":"Hamster resurrection: Pet rises from the grave at Easter after being buried in garden",
"description":"Tink the hamster was found ‘cold and lifeless’ in the bottom of her cage and laid to rest by a couple who were looking after her for a friend. But the next day the rodent – who was not dead but hibernating – reappeared as perplexed Les Kilbourne-Smith crushed a pile of old boxes for recycling...",
"answer":"true",
"fact": 15,
"fiction": 9,
"picture": "../../static/images/hamster.jpg"}]
for eachArticle in game_articles:
add_game_article(eachArticle["title"], eachArticle["description"], eachArticle["picture"], eachArticle["answer"], eachArticle["fact"], eachArticle["fiction"])
def add_game_article(title,description,picture, answer, fact=0, fiction=0):
games = GameArticle.objects.get_or_create(title=title)[0]
games.description=description
games.answer=answer
games.fact=fact
games.fiction=fiction
games.picture=picture
games.save()
return games
if __name__ == '__main__':
print("Starting FactOrFiction population script...")
populate()
fofgame.html:
{% extends 'factorfiction/base.html' %}
{% load staticfiles %}
{% block title_block %}
FoF Game
{% endblock %}
{% block main_body_block %}
<div class="current_article">
<div class="row">
<h1 id="game_title"></h1>
</div>
<div class="row">
<p id="game_description">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean
commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus
et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis,
ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</p>
</div>
<button id="game_fact" type="button">Fact</button>
<p id="game_or">OR</p>
<button id="game_fiction" type="button">Fiction</button>
<img id="game_picture" src='{% static "images/fakenews.jpg" %}' alt="Article Picture" />
<div id="answer">
<h1 id="your_answer"></h1>
<p id="current_answer">Currently, other users have said:</p>
<p id="current_answer_fact"></p>
<p id="current_answer_fiction"></p>
<button id="game_next" type="button">Next</button>
<a href="{% url 'index' %}"><button id="game_home" type="button">Homepage</button></a>
</div>
</div>
{% endblock %}
答案 0 :(得分:0)
以下是ajax-request的示例。单击一个按钮时会触发它并向{%url“ajax_requests”%}发出POST请求。成功地将一些数据加载到div ... console.log()仅用于检查返回的数据。
<script>
$("#button1").click(function () {
var itemid=1;
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
$.ajax({
url: '{% url "ajax_requests" %}',
type: 'POST',
data: {
'item_id': itemid,
},
dataType: 'json',
success: function (data) {
if (data) {
console.log(data);
html = '<img src="/user_images/' + data[6].fields.requesting_user[2] + ' "class="img-responsive" alt="Kuva">';
$("#test").append(html);
}
}
});
});
</script>
因此,为了完成这项工作,您需要添加一个视图并从your_app / urls.py指向它。像这样:
url(r'^ajax_requests/', ajaxrequests_view, name='ajax_requests'),
并在views.py中查询数据,然后将其序列化为json并返回:
def ajaxrequests_view(request):
item_id = request.POST.get('item_id', None)
get_data = MyModel.objects.select_related('item_owner').filter(item_id=item_id)
ser_data = serializers.serialize("json", get_data)
return HttpResponse(ser_data, content_type="application/json")