Javascript syntax error in Django template when variable value is missing

I have a Django template with an AJAX menu (where clicking on various menu items reloads part of the page). Each click of the menu calls up the Django view function through AJAX and returns some data that will be displayed on the page.

I load all the JS needed for all menu items only on the main page (since I found out that AJAX is not very good at returning JS in a <div> and then use eval () to execute it). Since I load all JS only on the main menu page, the data is obviously not available in other menu options at startup, as they will appear later when the corresponding view is called up (when the menu button is pressed)

Because of this, code like the one below gives a syntax error on the console, since JS is only parsed for the first time.

 <script> var data = {{se_data|safe}}; </script> 

Now I can not use the data returned from the view, even after I click on the menu items, since the crash in JS was not performed in the first place. I tried to use if to execute the code only when choosing the appropriate menu option, but that didn't work either, since the parser just parses everything.

I am trying to use different methods to solve a problem, but it seems I have not found an effective way to solve this problem. An alternative may be that the view function returns all the data only at first, but I fear that the menu options and the returned data may increase over time, which will delay the initial loading of the main menu page.

This is ajax menu click function:

 $(".ent-menu li a").click(function(e) { e.preventDefault(); // prevent from going to the page mentioned in href // get the href var href = $(this).attr("href"); $("#data_container").load(href, function() { load_data(); //this function uses the data variable defined earlier }); }); 

The error that I see in the console when loading the main menu page:

 Uncaught SyntaxError: Unexpected token ; at line 1110 data = ; 

because the data is not yet available.

0
source share
1 answer

As discussed, you should use JSON to send data from Python to JS; use JSON.parse() to deserialize the data to use in your JS.

+1
source

Source: https://habr.com/ru/post/1210520/


All Articles