jQuery.ajaxでJSON形式のデータを処理するときのメモ : JavaScript

Pocket

JSON形式データをjQuery.ajaxで送受信するときのメモ。

» jQuery.ajax() – jQuery API
» http://docs.jquery.com/Ajax_Events

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>Ajax sample used jQuery</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript" src="ajax.js"></script>
</head>
</head>
<body>
<h3>jQuery.ajax使ったフォームデータ送信サンプル</h3>
<form action="#">
    <input type="text" name="element1">
    <input type="text" name="element2">
    <input id="send" type="submit" value="送信">
</form>
<div id="response"></div>
</body>
</html>
jQuery(function($) {
    $('#send').click(function() {

        // ポストデータ
        var data = {};
        data.element1 = $('input[name="element1"]').val();
        data.element2 = $('input[name="element2"]').val();

        // Ajax通信
        $.ajax({
            url: './ajax.php',
            type: 'POST',
            success: function(response) {
                $('#response').text(response.element1 + ' : ' + response.element2);
            },
            data: data,
            dataType: 'json'
        });
        return false;

    });
});

dataTypeはサーバーが返すデータタイプを指定する。指定がないときはサーバーレスポンスのMIME typeから推測する。指定可能なデータタイプはxml, json, script, or html。

The type of data that you’re expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

本記事はJSONを前提として書いている。

<?php
$response = array(
    'element1' => $_POST["element1"],
    'element2' => $_POST["element2"],
);
header("Content-Type: application/json; charset=utf-8");  // ---1
echo json_encode($response); // ---2
  1. JSONを返すときのContent-Typeはapplication/json。
    » http://www.ietf.org/rfc/rfc4627.txt
  2. json_encode関数はJSON形式の文字列を返す。
    » PHP: json_encode – Manual

コメント

No comments yet.

コメントの投稿

改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。