我正面临一个小问题。我不得不将搜索引擎中的数据添加到网页中。有人可以指导我如何从字典中的列表中访问数据。 e .g
我编写以下代码以在控制台和网页中显示结果。
data = JSON.parse(result);
for (var item in data['data']['hits']['hits']) {
console.log(data);
$('.class name').each(function(){
$(this).append(data);
});
}
我必须访问名称和用户名。我编写上面的代码,但它只显示网页上的对象,在控制台中我可以从对象访问名称和user_name但在网页中我不知道如何执行此操作。
JSON格式是这样的
{
"data": {
"hits": {
"hits": [{
"_score": 1.8235999,
"_type": "xray",
"_id": "1234",
"_source": {
"user_name": "kamil",
"name": "ahmed"
},
"_index": "mri",
.....
]
}
}
}
我的问题是如何从此JSON格式访问name
和user_name
,以便将其附加到网页。
答案 0 :(得分:0)
你可以试一试这样做:
function getSourceProps(source) {
if(source){
return {
usernname: source["user_name"],
name: source["name"]
};
}
return {};
}
data = JSON.parse(result);
var hits = data['data']['hits']['hits'];
// You could simply use a for. The for...in structure is used for other purposes.
for (var i=0; i<hits.length; i++) {
// I can't understand why you make this selection. So I left it.
$('.class name').each(function(){
var props = getSourceProps(hits["source"]);
if(props.length){
$(this).append(props.username+" "+props.name);
}
});
}
基于此,您可以应用于整个阵列。
<!DOCTYPE html>
<html ng-app="angularJS">
<head>
<script src="/bower_components/angular/angular.js"></script>
<script src="app.js"></script>
<script src="controller.js"></script>
</head>
<body>
{{"Type your name"}}
<div ng-controller="angularJSCtrl as kontrol">
<button ng-click ="kontrol.sayHello()"> Click here </button>
<input type="text" ng-model="kontrol.name">
<h3> All students list </h3>
<div ng-repeat="el in kontrol.studentObj">
<div ng-show="{{ el.age < 20 }}"> {{el}}</div>
</div>
<includer></includer>
<br>
{{ kontrol.price | currency}}
<br>
{{ kontrol.date | date}}
</div>
答案 1 :(得分:0)
您要追加item
这是根对象,而是附加data = JSON.parse(result);
var list = data['data']['hits']['hits'];
for (var item in list) {
console.log(data);
$('.class name').each(function(){
$(this).append(item['_score']);//or any other property in the object inside list
});
}
。
例如
private void checkBox1_Click(object sender, EventArgs e) {
checkBox1.CheckState = checkBox1.CheckState == CheckState.Checked ?
CheckState.Unchecked : CheckState.Checked;
}
答案 2 :(得分:0)
我做了一个小例子,也许这有帮助:
var data = {
"data": {
"hits": {
"hits": [{
"_score": 1.8235999,
"_type": "xray",
"_id": "1234",
"_source": {
"user_name": "kamil",
"name": "ahmed"
},
"_index": "mri"
},{
"_score": 1.8235999,
"_type": "xray",
"_id": "1234",
"_source": {
"user_name": "username2",
"name": "hello"
},
"_index": "mri"
},{
"_score": 1.8235999,
"_type": "xray",
"_id": "1234",
"_source": {
"user_name": "username 3",
"name": "asdf"
},
"_index": "mri"
}]
}
}
};
for (var hit in data.data.hits.hits) {
var hit = data.data.hits.hits[hit];
var source = hit._source;
var index = hit._index;
var id = hit._id;
$('div').append(source.user_name + ' - ' + source.name + '<br/>');
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
&#13;