I am trying to send URL parameters to an API I wrote on Python, using Javascript. My Javascript code is as follows:
function createGetRequest() {
var request = new XMLHttpRequest();
request.open('GET', 'some-link/api/', true);
request.onload = function() {
var data = JSON.parse(this.response);
document.getElementById("idk").innerHTML = data.news.entry_news_item_title + "</br>" + data.news.entry_news_item_snippet + "</br>"
+ data.news.entry_news_item_url;
}
request.send();
}
and my Python REST API code is as follows;
def index():
NewsFeed = feedparser.parse("https://trends.google.com.tr/trends/trendingsearches/daily/rss?geo=TR")
entry = NewsFeed.entries[0]
return {"news" : {"Status" : "OK",
"item" : entry['title'],
"entry_news_item_title" : entry['ht_news_item_title'],
"entry_news_item_snippet" : entry['ht_news_item_snippet'],
"entry_news_item_url" : entry['ht_news_item_url']}}
I want to be able to get the index of the entry from the user and then return the corresponding entry. In other words, I want the entry = NewsFeed.entries[0]
part to accept a variable rather than a 0. I have tried everything online yet I can't seem to figure it out.
In your JavaScript code add entry to GET request as follows:
function createGetRequest() {
// code to get number/id you are clicking on
entry_id = getEntryId();
var request = new XMLHttpRequest();
//After question marks you can input your GET request parameters
request.open('GET', `some-link/api/?entry=${entry_id}`, true); //I am using backticks as interpolation
request.onload = function() {
var data = JSON.parse(this.response);
document.getElementById("idk").innerHTML = data.news.entry_news_item_title + "</br>" + data.news.entry_news_item_snippet + "</br>"
+ data.news.entry_news_item_url;
}
request.send();
}
In you Python code you need just to collect get parameters from request string as follows:
# Add the request parameter to the function
def index(request):
NewsFeed = feedparser.parse("https://trends.google.com.tr/trends/trendingsearches/daily/rss?geo=TR")
# Get the parameter from request
# By using get function if you do not have a parameter with given key it will return None
entry_id = request.GET.get('entry')
if entry_id:
entry = NewsFeed.entries[entry_id]
return {"news" : {"Status" : "OK",
"item" : entry['title'],
"entry_news_item_title" : entry['ht_news_item_title'],
"entry_news_item_snippet" : entry['ht_news_item_snippet'],
"entry_news_item_url" : entry['ht_news_item_url']}}
else:
# Handle bad request
return {"news":None}
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.