Javascript 如何从给定的代码中获取JSON对象?
我正在使用url我的代码是:Javascript 如何从给定的代码中获取JSON对象?,javascript,json,Javascript,Json,我正在使用url我的代码是: var url="http://nucleus/api/projectlist?format=json" var json=JSON.parse(this.responseText); 浏览器中JSON格式的数据如下所示 { "1": { "id": "91", "title": "Nucleus Aura", "project_locations": "TVm, Kochi", "proj
var url="http://nucleus/api/projectlist?format=json"
var json=JSON.parse(this.responseText);
浏览器中JSON格式的数据如下所示
{
"1": {
"id": "91",
"title": "Nucleus Aura",
"project_locations": "TVm, Kochi",
"project_type": "Villa",
"project_status": "Book Now",
"count_plan": 0,
"image": "uploads/project_images/projects_images_image1415954647.png",
"imagetitle": "Villa Night"
}
}
我想将JSON数据对象打印到警报框。将其分配给
var
以获取对象。如果responseText为
{
"one": {
"id": "91",
"title": "Nucleus Aura",
"project_locations": "TVm, Kochi",
"project_type": "Villa",
"project_status": "Book Now",
"count_plan": 0,
"image": "uploads/project_images/projects_images_image1415954647.png",
"imagetitle": "Villa Night"
}
}
那么
请澄清你的问题…只是为了确认。。。您正在进行实际的AJAX调用(即使您没有发布代码),对吗?如果没有,您需要进行AJAX调用以使其工作。请使用
{}
格式化代码!谢谢vikrant,但我没有使用jquery,我想从url var url=“”;var json=json.parse(this.responseText);如果this.responseText
提供了json字符串,那么您可以将其分配给var
并发出警报,然后立即测试答案!请再次检查我的问题。。。vikrant对于troublerex很抱歉,当按钮onclick事件发生时,如何添加此代码以执行?你能帮我吗?
getJSON(url, function(json){
alert(json);// will give output like [object][Object]
alert(json.one.id);// will give output 91
}
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
var url = "http://nucleus/api/projectlist?format=json";
getJSON(url).then(function(data) {
alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});