如何将JSON数据转换为javascript并显示在HTML上
我试图从我的服务器获取JSON数据,并操纵价格进行比较。我相信JavaScript是正确的语言,但我可能错了 我将从html上的表单中获取输入,在“Shell”和“ARCO”之间切换,还可以添加位置的总成本,并能够在其他功能中使用该成本 我可以将单个项目放入一个可以随时间变化的变量中吗如何将JSON数据转换为javascript并显示在HTML上,javascript,html,json,Javascript,Html,Json,我试图从我的服务器获取JSON数据,并操纵价格进行比较。我相信JavaScript是正确的语言,但我可能错了 我将从html上的表单中获取输入,在“Shell”和“ARCO”之间切换,还可以添加位置的总成本,并能够在其他功能中使用该成本 我可以将单个项目放入一个可以随时间变化的变量中吗 谢谢 我将根据我对这个问题的理解来回答这个问题,也就是从json文件中读取数据,以便在html页面中使用它 //This is our Ajax function to load the JSON data
谢谢 我将根据我对这个问题的理解来回答这个问题,也就是从json文件中读取数据,以便在html页面中使用它
//This is our Ajax function to load the JSON data
function ajaxLoad(path,callback){
try{
var response;
var xmlhttp =new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if(this.readyState==4&&this.status==200) {
response=this.responseText;
callback(response);
}
}
xmlhttp.open("POST",path,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
catch(e){
alert(e.message);
}
}
//now load the data
var itemsData;
var shellProds=[];
var arcoProds=[];
ajaxLoad("Items.json",function(data){
itemsData=JSON.parse(data);
for(i in itemsData.items){try{
if(itemsData.items[i].location=="shell"){
shellProds[i].itemid=itemsData.items[i].itemid;
shellProds[i].name=itemsData.items[i].name;
shellProds[i].price=itemsData.items[i].price;
}else{
arcoProds[i].itemid=itemsData.items[i].itemid;
arcoProds[i].name=itemsData.items[i].name;
arcoProds[i].price=itemsData.items[i].price;
}
//now you have loaded the data.
}
catch(e){
alert(e.message);
}
}
});
现在您有了两个加载了数据的对象数组。@fuzzle:如果您只想解析JSON,就不需要jQuery。当然,这是完全可能的。JavaScript内置了对JSON解析的支持,并且可以访问DOM。是的,你可以
var data=JSON.parse(yourJson)编码>并将数据用作关联数组