为什么无法访问json? [英] Why cannot access json?
问题描述
function loadResponse(filter) {
$.ajax({
type: 'GET',
url: 'path/to/example.json',
dataType: 'json',
cache: false,
beforeSend: function () {
console.log('loading');
},
success: function (response) {
//console.log('success, filtering response..');
var filtered = $(response).filter(function (i, n) {
return n.type === filter; //not working
});
console.log('filter by json ' + filtered);
for (var key in filtered) {
if (filtered.hasOwnProperty(key)) {
console.log('list ' + filtered[key]["description"]);
console.log('list ' + filtered[key]["name"]);
}
}
}
});
}
console.log
始终提供undefined
作为描述或名称.但无论如何,我都没有测试:
The console.log
kept giving undefined
for the description or name. But however I tested without:
var filtered = $(response).filter(function (i,n) {
return n.type === filter; //not working
});
能够在console.log
中获取描述和名称.好像$(response).filter
不会返回任何东西.不知道哪里出了问题.
Able to get description and name in console.log
. Seems like $(response).filter
does not return somthing. not sure where it went wrong.
更新
请参阅JSON-应该将响应打印出名称和类型.因此需要在json中过滤类型
See JSON -- response is supposed to print out name and type. so need to filter type inside json
[
{
"name": "Jonathan Suh",
"type": "zoologist, hobbyist"
},
{
"name": "William Philbin",
"type": "judge, hobbyist"
},
{
"name": "Allison McKinnery",
"type": "hobbyist"
}
];
$('.filter a').on('click', function(e){
e.preventDefault();
loadResponse($(this).attr('id'));
});
示例:
<a href='#' id="hobbyist">Hobbyist</a>
因此,请点击上方的此按钮,它应该会给我列出3个业余爱好者的列表.
So click on this above, it should give me list of 3 people who are hobbyists.
推荐答案
根据 API 过滤器将:
将匹配的元素的集合减少为与选择器匹配或通过功能测试的元素.
Reduce the set of matched elements to those that match the selector or pass the function's test.
(重点是我的)
我认为它适用于DOM元素而不是JSON对象
I think it works on DOM elements not JSON objects
您可以尝试使用 jquery.grep()
You can try using jquery.grep()
已更新
使用grep()
->单击时查看控制台以获取输出
Sample using grep()
-> See console for outputs when clicking
$(function() {
var arr = [{
"name": "Jonathan Suh",
"type": "zoologist, hobbyist"
}, {
"name": "William Philbin",
"type": "judge, hobbyist"
}, {
"name": "Allison McKinnery",
"type": "hobbyist"
}];
var doFilter = function(arr, filterParam) {
return jQuery.grep(arr, function(n, i) {
console.log(n.type.indexOf(filterParam));
return (n.type.indexOf(filterParam) > -1);
});
};
$(".filter").on('click', function() {
var filterName = $(this).attr('id');
console.log(filterName);
if (filterName) {
var filteredResults = doFilter(arr, filterName);
console.log(filteredResults);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>See console for outputs when clicking</h3>
<a href='#' class="filter" id="hobbyist">Hobbyist</a>
<br/>
<a href='#' class="filter" id="judge">Judge</a>
这篇关于为什么无法访问json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!