Import JSON file to JavaScript function

时间:2017-04-10 00:33:55

标签: django

Is it possible to import a JSON file into a JavaScript function? If yes, how can this be done the best practice way?

Below is my code with a few json rows and It'd be insane to have a million rows hardcoded in the function.

<script>
  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );
  </script>

1 个答案:

答案 0 :(得分:0)

你可以这样做:

var availableTags = JSON.parse("{{ context|escapejs }}");

然后你可以在Javascript中正常循环。

查看codepen。它显然在前端工作,问题可能在后端。