如何手动测试JavaScript?

时间:2016-05-24 22:00:34

标签: javascript html node.js forms

我试图通过使用Best Buy产品API制作简单的价格检查网站来学习javascript。

我如何"运行" javascript?我的表单接收产品ID号(SKU)并在提交时将其发送到validateSKU()。函数processData(data)使用SKU搜索产品。

当我测试网站时,什么也没发生,任何帮助都会很棒;谢谢!



<!DOCTYPE html>
<html>

<head>
  <title>Learn JavaScript</title>
</head>

<body>
  <form id="bestBuyForm" name="bestBuyForm" onsubmit="validateSKU()">
    <input id="SKU" name="SKU" required="" type="text">
    <label for="SKU">SKU</label>

    <input id="email" name="email" type="email">
    <label for="email">Email</label>

    <input class="button" id="submit" name="submit" type="submit">
  </form>
  <script>
    function validateSKU() {
      var SKU = document.forms["bestBuyForm"]["SKU"].value;
      var bby = require('bestbuy')('process.env.BBY_API_KEY');
      var search = bby.products('sku=' + SKU);
      search.then(processData);
    }

    function processData(data) {
      if (!data.total) {
        console.log('No products found');
      } else {
        var product = data.products[0];
        console.log('Name:', product.name);
        console.log('Price:', product.salePrice);
      }
    }
  </script>
</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

使用web console查看已发生的情况并阅读console API

尝试使用HTML元素addEventListener方法绑定validateSKU。此外,您应该防止在提交时导致页面重新加载的默认表单行为。致电event.preventDefault()

Working example代码:

<html>
  <form id="someForm">
      ...
      <button type="submit">Submit</submit>
  </form>
  <script>
    function validateSKU(event) {
      console.log('IT works');
      event.preventDefault();
      // ...here your code
    }

    var form = document.getElementById('someForm');

    form.addEventListener('submit', validateSKU, false);
  </script>
</html>