arrow_upward
closeサイドバー無

jQueryで外部ファイルを読み込む

あるファイルに他のファイルで作成した内容を呼び出します。
ここではonloadとajaxの方法となります。ajaxは昔はsucessで成功した場合呼び出せましたが、jQueryのバージョンが上がってdoneを使うようになっています。

onloadの場合

<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script>
    $(function(){
        $('b').on('click', function() {
            $("#note").load("test.html");
        });
    });
    </script>
</head>
<body>

    <p><a id="b">load</a></p>

    <div id="note"></div>

</body>
</html>

ajaxの場合

<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script>
    $(function(){
        $('a').on('click', function() {
            $.ajax({
                url: 'test.html',
            }).done(function(data){
                $('#note').html(data);
            }).fail(function(data){
                $('#note').html('失敗しました。');
            });
        });
    });
</script>
</head>
<body>

    <p><a id="a">ajax</a></p>

    <div id="note"></div>

</body>
</html>

ローカル環境(ブラウザ:chrome(管理者・--allow-file-access-from-filesを指定した状態でも))では成功となりませんでした。localhostやサーバーにアップしてからテストしたほうがよさそうです。私の環境だけかもしれませんがこれ以上調べるのが憂鬱だったのでこれでいいんじゃという感じに。セキュリティ難しいです。

関連記事

0 件のコメント:

コメントを投稿