【问题标题】:passing user input as parameter to src in html将用户输入作为参数传递给 html 中的 src
【发布时间】: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>&nbsp;</label>
        <input type="submit" value="Submit"/>
      </div>
    </fieldset>
  </form>
</body>

和src标签:

<script src="https://www.googleapis.com/customsearch/v1?key=MYKEY&amp;cx=017576662512468239146:omuauf_lfve&amp;q=VARIABLEHERE&amp;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&amp;cx=017576662512468239146:omuauf_lfve&amp;q='+param+'&amp;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


【解决方案1】:

如果你已经有了包含你想要的数据的变量,那么很容易将它插入到脚本标签的 src 属性中。

您可以使用 jquery 使用您的自定义 src 属性创建一个新的脚本标签:

var myData = "ThisDataHere";
$('<script>').attr({
    src: 'https://www.googleapis.com/customsearch/v1?key=MYKEY&amp;cx=017576662512468239146:omuauf_lfve&amp;q='+myData+'&amp;callback=hndlr',
    type: 'text/javascript'}).appendTo('body')

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多