我对 java 脚本没有太多经验,并且在 java 脚本回调方面遇到困难。我想知道这里是否有专家可以帮助我摆脱这段代码的困扰。 我的想法是,我正在尝试从 .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”返回一个 json 对象数组。 在第一个 getJSON 调用中,done 函数参数“data”包含这些 json 对象。 然后循环遍历每个对象并将它们一一传递到 formatItem 中。 这看起来是正确的。
在 find 方法中,您使用相同的 uri 'json.json',但在这里您不循环遍历对象,而是将它们全部发送到需要单个对象的 formatItem 函数。
因此,要从数组中获取具有 $('#KUNDE').val()
中 id 的对象,您可以对对象数组使用过滤器
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);
});
}
关于javascript - 使用 Javascript 和 jQuery 调用 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39342937/