How to get JSON from URL in JavaScript?

If you want to do it in plain javascript, you can define a function like this:

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.response);
      }
    };
    xhr.send();
};

有了 function 之後, use it like this:

getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback',
function(err, data) {
  if (err !== null) {
    alert('Something went wrong: ' + err);
  } else {
    alert('Your query count: ' + data.query.count);
  }
});

解法 2 jQuery,

jQuery.getJSON()
https://api.jquery.com/jQuery.getJSON/

Note that data is an object, so you can access its attributes without having to parse it.


jquery ajax 範例:

$.ajax({
url: '/your-url/enter',
type: 'GET',
timeout: 12000,  //單位:毫秒。
dataType: 'text'

}).done(function( responseText ){
$('#answer').text( responseText );

}).fail(function() {
alert('錯誤!');
});

資料來源
https://stackoverflow.com/questions/12460378/how-to-get-json-from-url-in-javascript

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *