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/
- jQuery.getJSON( url [, data ] [, success ] )
- urlType: StringA string containing the URL to which the request is sent.
- dataType: PlainObject or StringA plain object or string that is sent to the server with the request.
- successType: Function( PlainObject data, String textStatus, jqXHR jqXHR )A callback function that is executed if the request succeeds.
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