I'm developing a single page Flask app using AJAX to navigate through my routes. For example, when a user clicks on a nav-link, a GET request is made with AJAX that calls a route like "/profile", which returns a JSON including the HTML to be replaced on the screen.
If I type an existing route in the browser without calling an AJAX request, the HTML will be returned as expected as a JSON and simply pasted as text on the screen. I would like to give users the ability to type routes in the address bar and have the page load instead of just pasting the JSON with the HTML. What is the proper way to instead return a view instead of simply the JSON from my Flask end-point if no AJAX request was made (someone just types in "/profile" in the browser without clicking the profile nav-link)?
My first thought is to pass some type of parameter as part of every AJAX request and have the backend check if the parameter exists upon being called, where I would return a view instead of the JSON. That seems very inefficient and would make the code more complex by adding many more if statements. Additionally, I would have to create 2 HTML files for each route.
What is the proper way to go about this?
CodePudding user response:
If you are making an ajax request, you can add this into your route.
_xhr_key = request.headers.get('X-Requested-With')
if _xhr_key and _xhr_key == 'XMLHttpRequest': # if true this means that its an AJAX call
#return data for AJAX function
else:
#return data for regular request
#render HTML template to the user over here since its a regular request
Ajax Requests make an XMLHttpRequest object So if XMLHttpRequest object is present in the header then it means that it is an AJAX request. This is how you can load a webpage when a use normally loads it thus, you are able to render page using AJAX and when someone normally types the link in the browser