【问题标题】:How to use html form to submit API link to get JSON response如何使用 html 表单提交 API 链接以获取 JSON 响应
【发布时间】:2020-12-29 07:03:28
【问题描述】:

我正在为一家快递公司创建包裹跟踪表。

这是我的html表单

<h2>Track Package</h2>

<form>
  <label for="trackingno">Tracking No:</label>
  <input type="tel" id="trackingno" name="trackingno">
  <input type="submit" value="Submit">
</form>

公司已提供API链接

http://portal.activecourier.pk/api/v1/packet/00003711/status

当我点击这个链接时,我会得到这个数据

{"packet_id": "0024-00003711", "consignee_name": "Nasir maqbool", "destination": "Lahore", "current_status": {"status": "Assigned to Courier", "datetime": "2020-12-27T17:55:05.414Z", "comment": null}, "statuses": [{"status": "Pickup request sent", "datetime": "2020-12-27T09:55:41.295Z", "comment": null}, {"status": "Booked", "datetime": "2020-12-26T10:13:15.333Z", "comment": null}]}

我想使用 html 表单,以便访问者输入他的包裹跟踪 # 并获取他的包裹详细信息

【问题讨论】:

    标签: javascript php html json


    【解决方案1】:

    他们通常使用 jquery 来做到这一点

    $('#submit').click(function() {
      const response = $('#response');
      const trackingId = $('#trackingId').val();
      let html = '';
      $('#trackingId').val('');
      response.html('Please Wait');
      $.get('http://portal.activecourier.pk/api/v1/packet/'+trackingId+'/status', function(data) {
        html += '<div><strong>Packet Id:</strong> '+data.packet_id+'</div>';
        html += '<div><strong>Consignee Name:</strong> '+data.consignee_name+'</div>';
        html += '<div><strong>Current Status:</strong> '+data.current_status.status+' at '+data.current_status.datetime+'</div>';
        let statuses = data.statuses.map((e) => {
          return e.status + ' at ' + e.datetime
        });
        html += '<div><strong>Statuses:</strong> <ul><li>'+statuses.join('</li><li>')+'</li></ul></div>';
    
        response.html(html);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="response"></div>
    <input type="text" id="trackingId"/>
    <button type="button" id="submit">Submit</button>

    【讨论】:

    • 先生,我使用此代码,但它返回 Please Wait msg only
    • @HannahJames 这是因为本站的协议是https,本站不支持https。如果你在http协议上使用这段代码效果很好
    • 谢谢@Mohammad ...我可以使用你的代码得到结果:) 你能帮我输出 current_status 和 statuses 结果,因为 statuses 在循环中
    猜你喜欢
    • 1970-01-01
    • 2011-02-26
    • 2018-02-05
    • 1970-01-01
    • 2015-06-10
    • 2021-04-23
    • 1970-01-01
    • 2014-12-08
    • 2016-05-22
    相关资源
    最近更新 更多