2015-03-19 31 views
-3

我使用的URL我的代碼是:如何從給定的代碼中獲取JSON對象?

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數據對象的警告框。

+1

澄清你的問題,請... – n00dl3 2015-03-19 09:59:36

+0

確認一下...你是做實際的AJAX調用(即使你沒有發佈該代碼)是否正確?如果沒有,您需要通過AJAX調用才能正常工作。 – scunliffe 2015-03-19 10:20:16

+0

使用'{}'格式化代碼! – Vikrant 2015-03-19 10:25:05

回答

0

將其指定給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" 
    } 
} 

然後,

getJSON(url, function(json){ 
    alert(json);// will give output like [object][Object] 
    alert(json.one.id);// will give output 91 
} 
+0

感謝vikrant,但我不使用jquery我想從網址獲取它var url =「http:// nucleus/api/projectlist?format = json」; var json = JSON.parse(this.responseText);我如何顯示值到一個警告框 – user3171896 2015-03-19 10:09:44

+0

如果'this.responseText'給你的json字符串,那麼你可以將它分配給'var'並且只是提醒它 – Vikrant 2015-03-19 10:14:54

+0

現在試試這個答案! – Vikrant 2015-03-19 10:17:17

0
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.'); 
}); 
+0

@user,檢查.. – 2015-03-19 10:28:28

+0

rex如何添加此代碼來執行按鈕onclick事件?你能幫我嗎? – user3171896 2015-03-19 10:37:04