2012-03-29 27 views
36

我有一個類似於https://www.googleapis.com/freebase/v1/text/en/bob_dylan的外部資源,它返回一個JSON。我想在html中顯示結果鍵值(可以說div的名稱是「summary」)。結果鍵的值也應以純文本顯示。
的URL返回JSON:從外部URL獲取JSON數據並以純文本形式顯示在div中

{「結果」:「鮑勃·迪倫,出生羅伯特艾倫齊默曼,是美國 的創作型歌手,作家,詩人和畫家,誰是一個重大 人物在流行音樂爲五個十年。大部分從20世紀60年代,迪倫最 著名作品的日期,當他成爲一個.......」}

的JSON剛剛結果的關鍵,沒有其他的按鍵
基本上我不想使用純HTML和JavaScript以外的任何東西。我是JavaScript的初學者,因此我要求提供註釋代碼。

+0

這是一個相當基本的HTML/AJAX問題。你目前有什麼代碼?你卡在哪裏?這裏是AJAX的jQuery文檔,專門爲JSON數據做一個'GET':http://api.jquery.com/jQuery.getJSON/ - 你可能碰到的問題是同源策略,因爲你會針對不同於你的腳本運行的域的AJAX請求。 – 2012-03-29 09:12:49

回答

24

你可以用JSONP做到這一點是這樣的:

function insertReply(content) { 
    document.getElementById('output').innerHTML = content; 
} 

// create script element 
var script = document.createElement('script'); 
// assing src with callback name 
script.src = 'http://url.to.json?callback=insertReply'; 
// insert script to document and load content 
document.body.appendChild(script); 

但源必須意識到,你想它來調用回調參數傳遞給它的功能。

與谷歌API就應該是這樣的:

function insertReply(content) { 
    document.getElementById('output').innerHTML = content; 
} 

// create script element 
var script = document.createElement('script'); 
// assing src with callback name 
script.src = 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply'; 
// insert script to document and load content 
document.body.appendChild(script); 

檢查數據如何看起來當你通過回調到谷歌的API,如: https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply

這裏是JSONP的相當不錯解釋:http://en.wikipedia.org/wiki/JSONP

8

由於這是一個外部資源,您需要使用JSONP,因爲Same origin policy
要做到這一點,你需要添加查詢參數callback

$.getJSON("http://myjsonsource?callback=?", function(data) { 
    // Get the element with id summary and set the inner text to the result. 
    $('#summary').text(data.result); 
}); 
+0

這對我來說就是抓住JSON gravatar配置文件。 – KryptoniteDove 2013-01-21 15:38:09

+0

我得到了關於代理的'HTTP 407'錯誤 – 2013-07-10 16:48:16

+15

OP要求「plain HTML and JavaScript」 – Costa 2014-06-09 02:38:37

-1

由於所需的頁面會從不同的域叫你需要返回JSONP代替JSON的。

$.get("http://theSource", {callback : "?" }, "jsonp", function(data) { 
    $('#summary').text(data.result); 
}); 
2

您可以使用$ .ajax調用來獲取該值,然後將其放入您想要的div。你必須知道的一件事是你無法接收JSON數據。你必須使用JSONP。

代碼將是這樣的:

function CallURL() { 
    $.ajax({ 
     url: 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan', 
     type: "GET", 
     dataType: "jsonp", 
     async: false, 
     success: function(msg) { 
      JsonpCallback(msg); 
     }, 
     error: function() { 
      ErrorFunction(); 
     } 
    }); 
} 

function JsonpCallback(json) { 
    document.getElementById('summary').innerHTML = json.result; 
} 
+0

它要以div顯示,但json對象要創建 – nbhatti2001 2013-04-26 15:09:59

29

這裏是一個沒有使用JQuery使用純JavaScript。我使用的JavaScript的承諾和XMLHttpRequest的 在這裏你可以試試這個fiddle

HTML

<div id="result" style="color:red"></div> 

的JavaScript

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(); 
    }); 
}; 

getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan').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.'); 
}); 
+4

Promise不被舊版瀏覽器支持。 – 2015-02-19 14:17:17

+0

在最新版本的Chrome中,「then」函數的第一部分起作用,如果URL正確,我會得到結果。但是,如果網址不正確,我永遠不會收到「出現問題」警報。 也許這與小提琴手的工作方式有關? – 2015-09-10 20:00:48

+0

*任何*版本的Internet Explorer都不支持承諾* http://caniuse.com/#feat=promises並且您不需要*承諾簡單的HTTP請求... – nelsonic 2016-02-22 16:42:41

3

如果你想使用普通的JavaScript,但要避免的承諾,你可以使用拉米Sarieddine的解決方案,但用這樣的回調函數替代承諾:

var getJSON = function(url, callback) { 
    var xhr = new XMLHttpRequest(); 
    xhr.open('get', url, true); 
    xhr.responseType = 'json'; 
    xhr.onload = function() { 
     var status = xhr.status; 
     if (status == 200) { 
     callback(null, xhr.response); 
     } else { 
     callback(status); 
     } 
    }; 
    xhr.send(); 
}; 

而你也這樣稱呼它:

getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan', function(err, data) { 
    if (err != null) { 
    alert('Something went wrong: ' + err); 
    } else { 
    alert('Your Json result is: ' + data.result); 
    result.innerText = data.result; 
    } 
}); 
+0

在這個解決方案中,我得到了Chrome中的「No」Access-Control-Allow-Origin'header'錯誤。沒有爲我工作。 – 2017-01-05 15:17:09

+1

你說得對。這隻適用於服務器聲明'Access-Control-Allow-Origin'頭並允許其他人訪問其資源的情況。否則,您將不得不使用JSONP(如果服務器支持它)或CORS代理服務器,它會下載數據併爲您設置標題。 – 2017-01-05 17:02:35

-1

要顯示使用羅賓·哈特曼代碼JSON數據。您需要添加下面的行。

他給出的代碼給了你Object,object。此代碼以更好的方式檢索數據。

result.innerText =JSON.stringify(data); 
+0

他說,「我想在html中顯示結果鍵值在div中」,這正是我和Rami Sarieddine的代碼所做的。你的代碼會顯示整個數據,這不是他想要的。 – 2017-03-28 14:27:53

相關問題