4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryとAjaxの使い方

Last updated at Posted at 2015-05-25

jQueryとAjaxを使ってwebページにテキストを挿入する。

Ajaxの使用により更新処理を行わず別のファイルからデータを取得し表示させることが可能
ただし、Ajaxではセキュリティー上の理由から、HTMLと同一ドメイン上にあるファイルしか取得できません。

使用するファイル

Sample.html

下記のテキストファイルからデータを取得し一部テキストを書き換えます。

Sample.txt

Sample.txtの内容を読み込み、p要素の「変更前」というテキストを「変更後」に置き換えます。

Sample.htmlコード

Sample.html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <meta http-equiv="Content-Script-Type" content="text/javascript" />
        <title>sample1</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript">
$(function(){
    $("button").click(function(){
        $("p").load("./Sample.txt");
    })
})
        </script>
    </head>
    <body>
        <button>変更</button>
        <p>変更前</p>
    </body>
</html>
Sample.txt
変更後

コード解説

functionの「$(セレクター).load(ファイル名);」でSample.txtを読み込み、クリックされることで更新処理を行わずHTMLの<p>の中身をSample.txtの中身に変更する。

コード実行結果

ボタンを押す
sample1.png→       sample1 (1).png

参考にしたページ
http://ascii.jp/elem/000/000/458/458236/

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?