将jquery与ejs模板一起使用

时间:2017-04-07 01:16:58

标签: javascript jquery ejs

我正在尝试在ejs模板中使用jquery,使用服务器发送到模板的数组使输入自动完成。我收到以下错误:

ReferenceError: /var/www/html/DM/views/formulaire.ejs:8
    6| <title>Formulaire </title>
    7| </head>
 >> 8| <%
    9| $( "#depart" ).autocomplete({
    10|   source: autoComp
    11| });

$ is not defined 

我做了一些研究,发现你不能使用客户端javascript(jquery)与服务器端javascript(ejs),但我没有找到任何解决方案。

以下是代码:

<!DOCTYPE html>
<html lang="fr">
<head>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<meta charset="UTF-8">
<title>Formulaire </title>
</head>
<body>
<script>
$( "#depart" ).autocomplete({
  source: autoComp
});
</script>

  <form action="/result" method="post">
    Départ:<input type="text" name="depart" id="depart"><br>
    Arrivée: <input type="text" name="arrivee"><br>
    <input type="submit" value="Chercher un itinéraire">
  </form>
  <%
  if(erreur){
    %> <p>Erreur lors de la saisie des stations</p>
    <%
  }
  %>
</body>
</html>

感谢您的帮助

编辑:不再出现错误,但自动完成功能不起作用。

2 个答案:

答案 0 :(得分:1)

您需要将客户端代码放在<script>代码

更改

<%
$( "#depart" ).autocomplete({
  source: autoComp
});
%>

<script>
    $( "#depart" ).autocomplete({
      source: autoComp
    });
</script>

把它放在头部或身体内

答案 1 :(得分:0)

我假设您正在操作中创建数组并将其传递给视图。然后,您必须再进一步一步,将其从服务器端视图引擎传递到实际的浏览器引擎。

<script>
  let autoComp = JSON.parse( `<%= JSON.stringify( autoComp ) %>` );

这是什么:

  • 告诉EJS引擎将数组呈现为JSON字符串
  • (请注意反引号,因为它是字符串,所以需要某种引号)
  • 然后,浏览器端的JS引擎通过JSON.parse运行该字符串。

显然,此功能只能单向运行;要将变量从浏览器获取到EJS,您需要提交操作(POST / GET)。

您可能还需要一些替换以使字符串更美观,例如:

function fixForJSON(val) {
  return val.replace(/'/g, '&apos;').replace(/\\/g, '\\\\');
}
function fixForDisplay(val) {
  return val.replace(/&apos;/g, "'").replace(/\\\\/g, '\\');
}

如果您真的想这样做:

<%
  $(selector).doStuff();

您需要将JQuery对象本身传递到模板变量中。

例如在您的节点代码中:

const jsdom = require('jsdom');
const jquery = require('jquery');
const { JSDOM } = jsdom;
const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
const $ = jquery(dom.window);
global.jq = $;

然后在您的特定路由操作中(静态节点代码)

var locals = { // the var you are sending to the EJS template
  jq: global.jq,

最后在您的EJS中,您可以:

const $ = jq;
var testDiv = $('<div>').html('hello jquery in the template').appendTo('body');
console.log($('body').html());