简体   繁体   English

从外部URL获取JSON数据并将其作为纯文本显示在div中

[英]Get JSON data from external URL and display it in a div as plain text

I have an external resource similar to https://www.googleapis.com/freebase/v1/text/en/bob_dylan which returns a JSON. 我有一个类似于https://www.googleapis.com/freebase/v1/text/en/bob_dylan的外部资源,它返回一个JSON。 I want to display the value of result key in a div in html (lets say the name of the div is "summary"). 我想在html中的div中显示结果键的值(假设div的名称是“summary”)。 Also the value of result key should be displayed in plain text. 结果键的值也应以纯文本显示。
The URL returns the json: URL返回json:

{ "result": "Bob Dylan, born Robert Allen Zimmerman, is an American singer-songwriter, author, poet, and painter, who has been a major figure in popular music for five decades. Much of Dylan's most celebrated work dates from the 1960s, when he became an ......." } {“结果”:“鲍勃·迪伦,出生于罗伯特·艾伦·齐默尔曼,是美国创作歌手,作家,诗人和画家,五十年来一直是流行音乐界的重要人物。迪伦最着名的作品大部分来自于20世纪60年代,当他成为.......“}

The JSON has just the result key, no other keys JSON只有结果键,没有其他键
Basically I do not want to use anything other than plain HTML and JavaScript. 基本上我不想使用除纯HTML和JavaScript之外的任何东西。 I am a relative beginner to JavaScript and therefore I ask for commented code. 我是JavaScript的初学者,因此我要求注释代码。

Here is one without using JQuery with pure JavaScript. 这是一个没有使用纯JavaScript的JQuery。 I used javascript promises and XMLHttpRequest You can try it here on this fiddle 我使用了javascript promises和XMLHttpRequest你可以在这个小提琴上试试

HTML HTML

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

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

You can do this with JSONP like this: 您可以使用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);

But source must be aware that you want it to call function passed as callback parameter to it. 但是source必须知道你希望它将函数作为回调参数传递给它。

With google API it would look like this: 使用谷歌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);

Check how data looks like when you pass callback to google api: https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply 当您将回调传递给google api时,请检查数据的样子: https//www.googleapis.com/freebase/v1/text/en/bob_dylan? callback = insertReply

Here is quite good explanation of JSONP: http://en.wikipedia.org/wiki/JSONP 以下是对JSONP的很好的解释: http//en.wikipedia.org/wiki/JSONP

Since it's an external resource you'd need to go with JSONP because of the Same origin policy . 因为它是一个外部资源,所以你需要使用JSONP,因为相同的原始策略
To do that you need to add the querystring parameter callback : 为此,您需要添加querystring参数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);
});

If you want to use plain javascript, but avoid promises, you can use Rami Sarieddine's solution, but substitute the promise with a callback function like this: 如果你想使用普通的javascript,但是避免使用promises,你可以使用Rami Sarieddine的解决方案,但用这样的回调函数替换promise:

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

And you would call it like this: 你会这样称呼它:

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

You can use $.ajax call to get the value and then put it in the div you want to. 您可以使用$ .ajax调用来获取值,然后将其放入您想要的div中。 One thing you must know is you cannot receive JSON Data. 您必须知道的一件事是您无法接收JSON数据。 You have to use JSONP. 你必须使用JSONP。

Code would be like this: 代码如下:

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

To display the Json data using Robin Hartman code. 使用Robin Hartman代码显示Json数据。 You need to add, the below line. 您需要添加以下行。

The code he gave gives you Object, object. 他给出的代码为您提供了Object,object。 this code retrieves the data in a better way. 此代码以更好的方式检索数据。

result.innerText =JSON.stringify(data);

Since the desired page will be called from a different domain you need to return jsonp instead of a json . 由于将从不同的域调用所需的页面,您需要返回jsonp而不是json

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM