programing

외부 URL에서 JSON 데이터를 가져와 일반 텍스트로 구분하여 표시

fastcode 2023. 4. 5. 22:20
반응형

외부 URL에서 JSON 데이터를 가져와 일반 텍스트로 구분하여 표시

JSON을 반환하는 https://www.googleapis.com/freebase/v1/text/en/bob_dylan과 유사한 외부 리소스가 있습니다.결과 키의 값을 html로 div에 표시하고 싶다(div의 이름은 "summary"로 한다).또한 결과 키의 값은 일반 텍스트로 표시되어야 합니다.
URL은 json을 반환합니다.

결과: 밥 딜런은 미국의 싱어송라이터이자 작가, 시인, 화가이며 50년간 대중음악의 주역이었다.딜런의 가장 유명한 작업 날짜의 대부분은 그가 ........}가 된 1960년대부터이다.

JSON에는 결과 키만 있고 다른 키는 없습니다.
기본적으로 플레인 HTML이나 JavaScript 이외에는 사용하고 싶지 않습니다.저는 JavaScript는 비교적 초보이기 때문에 코멘트 코드를 요청합니다.

다음은 순수 JavaScript에서 JQuery를 사용하지 않는 예입니다.javascript 약속과 XMLHttpRequest를 사용하였습니다. 바이올린으로 시험해 보세요.

HTML

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

자바스크립트

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

이것은, 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);

단, 콜백파라미터로 전달되는 함수를 소스는 인식하고 있어야 합니다.

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

Google api에 콜백을 전달했을 때 데이터가 어떻게 표시되는지 확인합니다.https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply

다음은 JSONP에 대한 좋은 설명입니다.http://en.wikipedia.org/wiki/JSONP

외부 리소스이므로 동일한 원본 정책 때문에 JSONP를 사용해야 합니다.
그러기 위해서는 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);
});

플레인 javascript를 사용하고 싶지만 약속을 회피하는 경우에는 Rami 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;
  }
});

$.ajax 호출을 사용하여 값을 얻은 후 원하는 div에 넣을 수 있습니다.한 가지 알아두셔야 할 것은 JSON Data를 받을 수 없습니다.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;
}

Robin Hartman 코드를 사용하여 Json 데이터를 표시합니다.아래 줄을 추가해야 합니다.

그가 준 암호는 오브젝트, 오브젝트입니다.이 코드는 더 나은 방법으로 데이터를 가져옵니다.

result.innerText =JSON.stringify(data);

원하는 페이지는 다른 도메인에서 호출되므로 json이 아닌 jsonp를 반환해야 합니다.

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

언급URL : https://stackoverflow.com/questions/9922101/get-json-data-from-external-url-and-display-it-in-a-div-as-plain-text

반응형