使用 Javascript 和 jQuery 调用 Web API

Calling the Web API with Javascript and jQuery

我对 java-script 没有太多经验,而且我对 java-script 回调有困难。我想知道这里是否有任何专家可以帮助我摆脱这段代码的困扰。 我的想法是我正在尝试从 .json 文件中回调并按 ID 搜索它。 我可以看到所有客户,但无法搜索任何客户。

这是我的代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Kunde</title>
</head>
<body>

    <div>
        <h2>Kunde</h2>
        <ul id="ALLEKUNDE" />
    </div>
    <div>
        <h2>Search by ID</h2>
        <input type="text" id="KUNDE" size="5" />
        <input type="button" value="Search" onclick="find();" />
        <p id="RESULTS" />
    </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script>
        var uri = 'json.json';

    $(document).ready(function () {
      // Send an AJAX request
        $.getJSON(url)
          .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
              // Add a list item for the product.
              $('<li>', { text: formatItem(item) }).appendTo($('#ALLEKUNDE'));
            });
          });
    });

    function formatItem(item) {
        //return item.name + item.phone;
        return item.ID  + item.name + item.phone + item.contact + item.balanceLCY + item.creditLimitLCY;
        //'ID= ' + item.ID, + 'name = ' + item.name, "<br />" + 'phone = ' + item.phone, "<br />" + 'contact = ' + item.contact, "<br />" + 'balanceLCY= ' + item.balanceLCY, "<br />" + 'creditLimitLCY = ' + item.creditLimitLCY
    }

    function find() {
      var id = $('#KUNDE').val();
      $.getJSON(uri)
          .done(function (data) {
            $('#RESULTS').text(formatItem(data));
          })
          .fail(function (jqXHR, textStatus, err) {
            $('#RESULTS').text('Error: ' + err);
          });
    }
    </script>
</body>
</html>

从你的代码中我可以看出 uri 'json.json' returns json 对象数组。 在第一个 getJSON 调用中,done 函数参数 'data' 包含这些 json 对象。 然后循环遍历这些对象中的每一个,并将它们一一传递到 formatItem 中。 这看起来是正确的。

在 find 方法中,您使用了相同的 uri 'json.json',但在这里您没有遍历对象,而是将它们全部发送到期望单个对象的 formatItem 函数。

因此,要从数组中获取 ID 在 $('#KUNDE').val() 中的对象,您可以对对象数组使用过滤器

var item = array.filter(function ( obj ) {
    return obj.ID  === id;
})[0];

并在您的查找函数中实现它

function find() {
  var id = $('#KUNDE').val();
  $.getJSON(uri)
      .done(function (data) {

        var item = data.filter(function ( obj ) {
                return obj.ID  === id;
            })[0];

        if( typeof item !== 'undefined' || item !== null ){
            $('#RESULTS').text(formatItem(item));
        }
      })
      .fail(function (jqXHR, textStatus, err) {
        $('#RESULTS').text('Error: ' + err);
      });
}