【问题标题】:Why is the API not working correctly?为什么 API 无法正常工作?
【发布时间】:2017-04-23 02:57:35
【问题描述】:

为什么提交按钮没有输出应有的结果?我似乎没有注意到代码可能有什么问题。基本上它是来自 Mashape (https://market.mashape.com/nviror/bmi-calculator) 的 BMI API,我无法让它工作。我是 JavaScript 和 API 的新手,所以我无法解决这个问题.. 这是 javascript 和 html 的表单部分:

// TODO: Use a function closure and release global $
$.noConflict();
(function($){
  $(document).ready(function() {
    $('#bmi-form').on('submit', function(event) {
      //saving inputs
      var weight = $('#bmi-weight').val();
      var height = $('#bmi-height').val();
      
      $.get(
          'https://bmi.p.mashape.com/WyFUMDOkdrmshARoxfXDWLZmMeccp180tJEjsnCz3MCFuXJdEo' + weight + height,
          function(data,json){
            $('#bmi').append(
            '<p>Your BMI is: '+data.bmi.value+'</p>'
          );
          $('#bmi').append(
            '<p>Your status is: '+data.bmi.status+'</p>'
          );
          $('#bmi').append(
           '<p>Your risk is: '+data.bmi.risk+'</p>'
          );
      });  
        var string= 'Your Bmi: ' +value+ '. Your status:' +status+ '. Your risk:' +risk + '.';
        $('#results').text(string);

    });
  event.preventDefault();
  });
});(jQuery);
<section id="bmi">
        <form id="bmi-form" name="bmi-form" method="get" action="#null">
          <label for="bmi-weight">Type in your weight:</label>
          <input type="text" id="bmi-weight" name="bmi-weight" />
          <label for="bmi-height">Type in your height:</label>
          <input type="text" id="bmi-height" type="text" name="bmi-height" />
          <input type="submit" id="bmi-submit" name="bmi-submit" value="Check BMI" />
        </form>
        <p id="results"></p>
      </section>

【问题讨论】:

  • 您链接的 API 正在使用 POST 请求,而您正在使用 GET 请求。您还需要将有效负载数据构建为 JSON
  • @OscarSiauw 所以你是说我选择的 API 不会像我预期的那样运行,我应该找到一个使用 GET 请求的 API?还是我做错了什么……
  • API 正确,但需要使用 POST 请求。并将您的有效负载构建为 JSON。 API 文档中的示例:{"weight":{"value":"85.00","unit":"kg"},"height":{"value":"170.00","unit":"cm"} ,"性别":"m","年龄":"24","腰围":"34.00","臀围":"40.00"}

标签: javascript html json api access-token


【解决方案1】:

做这样的事情:

注意:很遗憾我没有测试下面的代码

$.ajax(
    {
        method: "POST",
        url: "https://bmi.p.mashape.com/",
        headers: {
            "X-Mashape-Key": <enter your API key here>,
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        data: '{"weight":{"value":"85.00","unit":"kg"},"height":{"value":"170.00","unit":"cm"},"sex":"m","age":"24","waist":"34.00","hip":"40.00"}'
    }
).done(function(){
    console.log("Done");
})

【讨论】:

  • 这确实有效,但它会在页面加载时自动显示,当我按下提交按钮并使用表单中的值而不是 85 和 170 时,我需要它显示...但肯定有虽然取得了一些进展......
  • 然后在您的按钮单击事件中调用它。并使用表单中的值更改数据有效负载。我只是向您展示了如何使用 JSON 有效负载进行 POST 请求的示例
猜你喜欢
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多