我试图让jquery autocomplete函数在HtmlService模板中工作。当我提供它时,函数内部生成的数组按预期工作。我的想法是从ScriptDb数据库提供数据,我编写了一个从数据库返回数组的函数(按预期返回一个数组):
function doGet(e) {
var htmlTemplate = HtmlService.createTemplateFromFile('Search');
htmlTemplate.diseases = ['aname','bname','cname','dname','ename','fname','gname'];
Logger.log(htmlTemplate.diseases instanceof Array);
return htmlTemplate.evaluate();
}
在这种情况下,记录器返回true。
<!DOCTYPE html>
<html>
<head>
<!-- <title>The Disease Database</title> -->
<meta name="author" content="M. Oranje" />
<meta name="description" content="My personal disease database" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/smoothness/jquery-ui.css" rel="Stylesheet" />
</head>
<body>
<form action="https://script.google.com/macros/s/AKfycbxHmY6ejv8SnmnOupKKrieImaPTbCZAdtuQl_n8z78/dev" method="POST" id="diseases-form">
<div id="page">
<div class="search">
<div class="name" name="name" id="name">Search</div>
<div class="search_input"><input name="search" id="search" type="text"></div>
</div>
</div>
</form>
<script>
$(function() {
var tags = <?= diseases ?>;
alert(tags instanceof Array);
$( "#search" ).autocomplete({
source: tags
});
});
</script>
</body>
</html>
然而,此处警告返回false,并强制打印数组返回参考错误('aname未定义')。
答案 0 :(得分:2)
解决!需要JSON.stringify()才能正确转换。
$(function() {
var tags = <?!= JSON.stringify(diseases) ?>;
$( "#search" ).autocomplete({
source: tags
});
});