使用AJAX将RSS源传递到django视图

时间:2021-08-23 00:58:53

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. For performing same, I am using rss feeds from different sources. 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. Following is my view function and template(for cricket).

我是ajax的新手。以下是我的用例:我正在开发一个侧面项目,将显示新闻和各种不同的运动。为了执行相同的操作,我使用来自不同来源的RSS源。我可以使用'feedparser'插件在django视图中获取和解析rss提要,并将相同的上下文传递给相应的模板。以下是我的视图功能和模板(用于板球)。

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. I have written a script to check the

现在,我想使用AJAX仅重新加载我的页面的某些块,而不是重新加载和重定向整个页面。我写了一个脚本来检查

<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. Following is the script :

在我的urlChecker()脚本中,我检查单击了哪个锚标记并分配相应的URL。以下是脚本:

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. Please help

我不知道如何使用ajax将Feed数据发布到我的模板。请帮忙

1 个解决方案

#1


1  

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. 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请求更合适。您没有向他们需要存储的这些端点发送任何信息,但只想从中检索更新。这不会改变你的代码,你可以使用☞$ .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. 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).

发送GET请求也更容易,因为您不需要考虑☞Django的CSRF保护。发布其他ajax请求(如POST,DELETE等)也不是那么难,但它需要一个额外的步骤,包括在每个请求中发送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, e.g. 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.

目前,用于呈现Ajax结果的模板可能存在概念问题,例如: scorecenter / cricket.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. Let these templates only render exactly the html that you want to insert into the DOM with $('.testingData').html(data).

此外,由于您将通过Javascript将结果插入到已加载的网站中,因此您无需定义模板块。让这些模板只使用$('。testingData')。html(data)准确呈现要插入DOM的html。


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). Whenever an Ajax-request fails, it will display an error there, which you can then introspect.

在开发您的网站时,在浏览器中打开开发人员工具并在那里激活控制台(Firefox和Chrome都可以)。每当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. ☞ More complete list of status codes

常见错误是404(如果找不到端点),如果请求未被授权,则为400或403;如果服务器处理您的请求时出错,则为500。 ☞更完整的状态代码列表

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.

请随时更新您的问题以获取更多详细信息。由于这是一个非常广泛的主题,因此可能会被社区关闭。在这种情况下,您可以随时搜索更具体的问题,或者如果您没有找到答案,请将它们放在一个新问题中。

#1


1  

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. 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请求更合适。您没有向他们需要存储的这些端点发送任何信息,但只想从中检索更新。这不会改变你的代码,你可以使用☞$ .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. 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).

发送GET请求也更容易,因为您不需要考虑☞Django的CSRF保护。发布其他ajax请求(如POST,DELETE等)也不是那么难,但它需要一个额外的步骤,包括在每个请求中发送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, e.g. 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.

目前,用于呈现Ajax结果的模板可能存在概念问题,例如: scorecenter / cricket.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. Let these templates only render exactly the html that you want to insert into the DOM with $('.testingData').html(data).

此外,由于您将通过Javascript将结果插入到已加载的网站中,因此您无需定义模板块。让这些模板只使用$('。testingData')。html(data)准确呈现要插入DOM的html。


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). Whenever an Ajax-request fails, it will display an error there, which you can then introspect.

在开发您的网站时,在浏览器中打开开发人员工具并在那里激活控制台(Firefox和Chrome都可以)。每当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. ☞ More complete list of status codes

常见错误是404(如果找不到端点),如果请求未被授权,则为400或403;如果服务器处理您的请求时出错,则为500。 ☞更完整的状态代码列表

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.

请随时更新您的问题以获取更多详细信息。由于这是一个非常广泛的主题,因此可能会被社区关闭。在这种情况下,您可以随时搜索更具体的问题,或者如果您没有找到答案,请将它们放在一个新问题中。