Skip to content

Instantly share code, notes, and snippets.

@sundaycrafts
Last active September 5, 2015 14:32
Show Gist options
  • Save sundaycrafts/dd630376972f729cb6f3 to your computer and use it in GitHub Desktop.
Save sundaycrafts/dd630376972f729cb6f3 to your computer and use it in GitHub Desktop.
jq, js: Load HTML fragment with JQuery ajax() without $.load()
// この実装は$.load()に限りなく近い
// http://james.padolsey.com/jquery/#v=2.1.3&fn=jQuery.fn.load
// http://stackoverflow.com/questions/16885538/how-to-load-an-html-fragment-with-jquery-ajax
$.ajax({
url: 'page.html',
dataType: 'html'
}).done(responsText =>
// 空のdiv要素に追加
var $el = $('<div>').append($.parseHTML(responsText)).find('.selector');
// この処理は逐次的に行う必要がある。
// $elはDOMオブジェクトにキャストしなくとも正常に動作する(単にhtml($el)でも良い)。
$('body').html($el.get()[0]);
);
@sundaycrafts
Copy link
Author

もしも$.load()でエラー処理をしたいときは以下。
http://stackoverflow.com/questions/753300/how-to-catch-error-in-jquerys-load-method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment