[英]Fill a select with JSON values
I have a function that gets a json text from a certain website: 我有一个从某个网站获取json文本的函数:
window.onload = function httpGet()
{
var xmlHttp = null;
var box = document.getElementById("http") //just for testing
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://link_to_Json_Text", false );
xmlHttp.send( null );
box.value += xmlHttp.responseText; //just for testing
return xmlHttp.responseText.toJSON();
}
This dislays the results as: 结果显示为:
{
"head": {
"vars": [ "uri" , "label" ]
} ,
"results": {
"bindings": [
{
"uri": { "type": "uri" , "value": "http://tematres.befdata.biow.uni-leipzig.de/vocab/?tema=751" } ,
"label": { "type": "literal" , "xml:lang": "en" , "value": "15n" }
} ,
{
Then I perform this function to retrieve the values of the JSON as an object: 然后,我执行此函数以将JSON的值作为对象检索:
var results = httpGet().results.bindings.map(function(el){
return { uri: el.uri.value, label: el.label.value };
});
Then I would like to get the values of the second function in an HTML select menu. 然后,我想在HTML选择菜单中获取第二个函数的值。
I am not sure however, if the second method is correctly calling the first one, because the console dislays errors like : Uncaught ReferenceError: httpGet is not defined
但是,我不确定第二种方法是否正确地调用了第一种,因为控制台产生了如下错误:
Uncaught ReferenceError: httpGet is not defined
What I need is to use value
from label
to fill the select menu. 我需要使用
label
value
填充选择菜单。
Just chain the success event for the request: 只需为请求链接成功事件:
window.onload = function() //No function name needed
{
var xmlHttp = null;
var box = document.getElementById("http") //just for testing
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://link_to_Json_Text", false );
xmlHttp.send( null );
xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState==4 && xmlHttp.status==200)
{
var results =xmlHttp.responseText.toJSON();
results.bindings.map(function(el){
return { uri: el.uri.value, label: el.label.value };
});
}
};
}
This just make the httpGet request and wait for the request to end (readyState ==4) to trigger the funcionality for the results process. 这只是发出httpGet请求并等待请求结束(readyState == 4)来触发结果过程的功能。
Anyway I would like to recomend you if you can, using jQuery because is so much simpler to work with Ajax than native JS 无论如何,我想建议您使用jQuery,因为与本地JS相比,使用Ajax更加简单
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.