20140305【JS】jQueryでJSONPを取得する

お題

jQueryJSONPを取得する

プログラム概要

jQueryのgetJSON()メソッドを利用してJSONPを取得し画面に表示する

ソース


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>hoge</title>
<script src="jquery-1.11.0.js"></script>
</head>
<body>
<h1>AjaxでJSONを取得</h1>

<input type="button" id="get_json" value="実行"/>
<table id="books" border="1">
    <tr>
		<th>タイトル</th>
		<th>著者	</th>
	</tr>
</table>
<script>
$(function(){
	$.ajaxSetup({cache: false});
	$('#get_json').click(function(){
		$.getJSON('books.json',function(data, status, req){
			$.each(data, function(i, book){
				$('#books').append($('<tr>').append($('<td>').text(book.title)).append($('<td>').text(book.author)))
			});
		});
	});
});

</script>
</body>
</html>

実行結果

実行前:

f:id:mocomei:20140305210826p:plain

実行押下後:

f:id:mocomei:20140305210819p:plain