简体   繁体   中英

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. 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).

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.

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

<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 :

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

From the Ajax point of view

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() .


From the Django point of view

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).


Rendering the result from the Ajax request

Currently there might be a conceptual problem with the template that you use to render the Ajax results, eg 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 .

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) .


Debugging problems with Ajax requests

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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