Javascript Django-使用jQuery/AJAX访问数据库

Javascript Django-使用jQuery/AJAX访问数据库,javascript,jquery,ajax,django,Javascript,Jquery,Ajax,Django,我希望有人能帮助我,因为我已经尝试了很多次,但都没有成功。我曾尝试使用tango with django的书来适应这种情况,并在网上的许多其他例子中使用了同样的方法,但没有成功。无论如何 我目前正在与Django一起设计一个小型的“假新闻”网站,该网站有一个迷你游戏,向用户显示一篇新闻文章(标题、描述、图片),用户必须投票决定是“事实”还是“虚构”,然后告诉他们是否正确,以及之前有多少人投票赞成这个答案 如果我将所有数据都存储在javascript变量中,我可以让它完全正常工作,如下所示:

我希望有人能帮助我,因为我已经尝试了很多次,但都没有成功。我曾尝试使用tango with 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 %}
{%extends'factorfiction/base.html%}
{%load staticfiles%}
{%block title\u block%}
FoF游戏
{%endblock%}
{%block main_body_block%}

Lorem ipsum dolor sit amet,是一位杰出的足球运动员。埃尼安 康莫多·利古拉·埃吉特·多洛。埃尼安·马萨。佩纳提布自然社会酒店 等马格尼斯产褥的时候,你会发现它的。Donec quam felis, ultricies nec、Pelletsque eu、pretium quis、sem。这是一个很好的例子

事实

小说 目前,其他用户表示:

下一个 {%endblock%}
下面是一个ajax请求示例。它在单击按钮并向{%url“ajax_requests”%}发出POST请求时激发。如果成功,它会将一些数据加载到div。。。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>
在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")
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")