Reputation: 43
I need to download the headlines from BBC and using Ajax and jquery in Django. Im currently trying to use Urllib3, to create a request to get the RSS/XML Top News data from the BBC website found at the following:
'http://feeds.bbci.co.uk/news/rss.xml'
I have created the request I believe, but when the returned object pass it back to my HTML/Javascript it doesn't work and I get the following error.
the object I pass through the window.onload method is: upon_success({{ AllNews }})
and gives me the error 'Uncaught SyntaxError: Unexpected token &'
My HTML and Views.py:
from django.shortcuts import render
import urllib3
import urllib3.request
import json
def index(request):
http = urllib3.PoolManager()
r = http.request('GET', 'http://feeds.bbci.co.uk/news/rss.xml')
xml_news = r.data
context = {'AllNews': xml_news}
return render(request, 'home/NewsHome.html', context)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="application/javascript">
function upon_success (xml) {
alert('ok');
xml.find('item').each(function(){
var title = $(this).find('title').text();
msg =+ "<li> " + title + " </li>"
$("#AllNews ul").append(msg)
}
)};
{% if AllNews %}
window.onload = upon_success({{ AllNews | safe }});
{% endif %}
</script>
</head>
<body>
<h1>Top News: BBC versus CNN</h1>
<ul id="AllNews"></ul>
</body>
</html>
i don't understand how to pass the response object back to the Javascript so that i can try to extract the News titles! any information or advice would be much appreciated !
Upvotes: 1
Views: 223
Reputation: 20569
request
method won't return just plain text response, but python object containing response, status code, headers and some other data. It can't be passed directly to JavaScript.
If you want to pass just plain text response, change:
xml_news = r
to:
xml_news = r.data
It will contain plain XML response from RSS URL. You can parse it either in Python (and pass to javascript only meaningful values, in JSON format) or just pass it to javascript as is, handling it's parsing on javascript side.
Upvotes: 1