简体   繁体   English

使用AJAX将RSS feed传递到Django视图

[英]Passing RSS feeds to django view using AJAX

I'm pretty new to ajax.Following is my use case : I am developing a side project that will show news and scores of different sports. 我对ajax相当陌生,下面是我的用例:我正在开发一个附带项目,它将显示新闻和各种体育赛事的得分。 For performing same, I am using rss feeds from different sources. 为了执行相同的操作,我使用来自不同来源的rss feed。 I am able to fetch and parse the rss feeds in django views using 'feedparser' plugin, and passing the same as context to the corresponding template. 我能够使用'feedparser'插件在django视图中获取并解析rss feed,并将与上下文相同的内容传递给相应的模板。 Following is my view function and template(for cricket). 以下是我的查看功能和模板(用于板球)。

def cricket(request):
    feeds_cric = feedparser.parse('http://www.espncricinfo.com/rss/content/story/feeds/0.xml') #espncricinfo feed.
    feeds_cric_scores = feedparser.parse('http://static.cricinfo.com/rss/livescores.xml') #espncricinfo feed.
    context = {'feeds_cric': feeds_cric,'feeds_cric_scores' : feeds_cric_scores}
    return render(request,'scorecenter/cricket.html', context)

Following is the corresponding template. 以下是相应的模板。

{% extends "scorecenter/index.html" %}
{% block content %}
    <ul>
        {% for entry in feeds_cric.entries %}
        <li><a href="{{ entry.link }}">{{ entry.title }}</a></li>
        <p>{{ entry.description }}</p>
        {% endfor %}
    </ul>

{% endblock content %}

{% block score %}
    <ul>
        {% for entry in feeds_cric_scores.entries %}
        <li><a href="{{ entry.link }}">{{ entry.title }}</a></li>
        <!-- <p>{{ entry.description }}</p> -->
        {% endfor %}
    </ul>
{% endblock score %}    

Following is index.html file. 以下是index.html文件。

Now, I want to use AJAX to reload only certain blocks of my page, rather than reloading and redirecting the complete page. 现在,我想使用AJAX仅重新加载页面的某些块,而不是重新加载和重定向整个页面。 I have written a script to check the 我写了一个脚本来检查

<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#">Allscores</a>
            </div>
            <div>
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#" onclick="urlChecker('cricket')">Cricket</a></li>
                    <li><a href="#" onclick="urlChecker('football')">Football</a></li>
                    <li><a href="#" onclick="urlChecker('basketball')">Basketball</a></li>
                    <li><a href="#" onclick="urlChecker('tennis')">Tennis</a></li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="navbar navbar-default" id="empty_nav"></div>

    <div class="testingData">This should be updated</div>

    <div class="row">
        <div class="col-sm-8" id="news">

            <h3>Latest News</h3>
            {% block content %}
            {% endblock content %}

        </div>
        <div class="col-sm-4" id="scores">

            <h3>Latest scores</h3>
            {% block score %}
            {% endblock score %}

        </div>
    </div>

    <div id="footer">
        Copyright © acllscores.com
    </div>
</body>

In my urlChecker() script, I check which anchor tag is clicked and assign the corresponding url. 在我的urlChecker()脚本中,我检查单击了哪个锚标记并分配了相应的url。 Following is the script : 以下是脚本:

function urlChecker (route) {
    switch(route) {
        case 'cricket':
            $.post( "/scorecenter/cricket/", function( data ) {
                $( ".result" ).html( data );
            });
            break;
        case 'football':
            $.post( "/scorecenter/football/", function( data ) {
                $( ".testingData" ).html( data );
            });
            break;
        case 'tennis':
            $.post( "/scorecenter/tennis/", function( data ) {
                $( ".testingData" ).html( data );
            });
            break;
        case 'basketball':
            $.post( "/scorecenter/basketball/", function( data ) {
                $( ".testingData" ).html( data );
            });
            break;

    }
}

Update : Adding urls file : 更新:添加网址文件:

urlpatterns = patterns('',
    url(r'^$', views.index,name='index'),
    url(r'^test/$', views.test,name='test'),

    url(r'^cricket/$', views.cricket,name='cricket'),
    url(r'^basketball/$', views.basketball,name='basketball'),
    url(r'^football/$', views.football,name='football'),
    url(r'^tennis/$', views.tennis,name='tennis'),

)

I am not fathom how to post the feed data to my templates using ajax. 我不知道如何使用Ajax将提要数据发布到模板中。 Please help 请帮忙

From the Ajax point of view 从Ajax的角度来看

From what you write in the question it would be more appropriate to send a GET request rather than a POST request. 从您在问题中写的内容来看,发送GET请求而不是POST请求更为合适。 You are not sending any information to these endpoints that they need to store, but only want to retrieve updates from them. 您不会将任何信息发送到它们需要存储的这些端点,而只想从它们检索更新。 This doesn't change much of your code, you can do that with $.get() instead of $.post() . 这不会改变您的大部分代码,您可以使用$.get()代替$.post()


From the Django point of view 从Django的角度来看

Sending a GET request is also easier, since you don't need to account for ☞ Django's CSRF protection . 发送GET请求也更加容易,因为您无需考虑☞Django的CSRF保护 Issuing other ajax requests (like POST , DELETE , etc.) isn't all that hard either, but it requires an extra step that involves sending the CSRF token with every request (well documented in the linked docs). 发出其他ajax请求(例如POSTDELETE等)也不是那么困难,但是它需要一个额外的步骤,该步骤涉及随每个请求发送CSRF令牌(在链接的文档中有详细记录)。


Rendering the result from the Ajax request 呈现Ajax请求的结果

Currently there might be a conceptual problem with the template that you use to render the Ajax results, eg scorecenter/cricket.html . 当前,用于呈现Ajax结果的模板可能存在概念性问题,例如scorecenter/cricket.html On the very top you are extending from index.html , which means that each request will not only return the block of html that you want to insert but also anything that's part of index.html . 最顶层是从index.html扩展的,这意味着每个请求不仅将返回要插入的html块,还将返回index.html一部分的任何内容。

Also, since you will insert the results by Javascript into the already loaded website you don't need to define template blocks. 另外,由于您将通过Javascript将结果插入到已加载的网站中,因此无需定义模板块。 Let these templates only render exactly the html that you want to insert into the DOM with $('.testingData').html(data) . 让这些模板仅使用$('.testingData').html(data)精确呈现要插入到DOM中的$('.testingData').html(data)


Debugging problems with Ajax requests 使用Ajax请求调试问题

While developing your site, open the developer tools in your browser and activate the console there (either Firefox and Chrome are fine). 在开发网站时,请在浏览器中打开开发人员工具并在其中激活控制台(Firefox和Chrome都可以)。 Whenever an Ajax-request fails, it will display an error there, which you can then introspect. 每当Ajax请求失败时,它将在此处显示错误,然后您可以进行自省。

Common errors are 404 (if the endpoint couldn't be found), 400 or 403 if the request was not authorized or 500 if the server has an error processing your request. 常见错误为404 (如果找不到端点), 400403如果请求未被授权)或500如果服务器在处理您的请求时出错)。 ☞ More complete list of status codes ☞更完整的状态码列表

Feel free to update your question with more details. 请随时更新您的问题,并提供更多详细信息。 Since this is a very wide topic be prepared that it might be closed by the community. 由于这是一个非常广泛的主题,因此请做好准备,使其可能被社区关闭。 In that case you can always search for more specific questions or if you don't find answers, put them in a new question. 在这种情况下,您始终可以搜索更具体的问题,或者,如果找不到答案,请将其放在新问题中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM