【发布时间】:2017-12-18 15:23:35
【问题描述】:
我有一个 HTML 表单字段,我想在其中收集用户的输入,将其存储在变量中,然后传递给调用 Google 自定义搜索 API 的 src 标记。有没有办法只在前端工作?
表格:
<body>
<form id="InputForm" method="post" >
<fieldset>
<legend>Input Form</legend>
<div>
<label for="Task">To do...</label>
<input type="text" id="Task" value="" style="width: 600px;" />
</div>
<div class="submitLabel" style="margin-left: 425px;">
<label> </label>
<input type="submit" value="Submit"/>
</div>
</fieldset>
</form>
</body>
和src标签:
<script src="https://www.googleapis.com/customsearch/v1?key=MYKEY&cx=017576662512468239146:omuauf_lfve&q=VARIABLEHERE&callback=hndlr">
我尝试使用 getElementByID 将用户输入存储在变量中,但尝试将变量插入 src 属性中没有成功。
var param = document.getElementById("Task").value;
var script = document.createElement("script");
script.src = "https://www.googleapis.com/customsearch/v1?key=MYKEY&cx=017576662512468239146:omuauf_lfve&q='+param+'&callback=hndlr"
document.getElementsByTagName("script")[0].parentNode.appendChild(script);
hndlr 函数格式化并显示 API 返回的结果。它在我使用预定义的 q 参数时起作用。
【问题讨论】:
-
I tried to store the user input in a variable by using getElementByID, but have had no success with trying to insert the variable in the src attribute.- 请分享此代码,以便我们了解它为什么不起作用。有关详细信息,请参阅How to create a Minimal, Complete, and Verifiable example。 -
已添加代码。这是根据我发现的另一个问题的解决方案改编的,但我对前端语言非常陌生,所以我不确定 HTML DOM 是否可以与 Javascript 一起使用。
标签: javascript jquery html google-api google-custom-search