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


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

<!DOCTYPE html>
<html lang="ja">
    <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>
<form action="#">
    <input type="text" name="element1">
    <input type="text" name="element2">
    <input id="send" type="submit" value="送信">
<div id="response"></div>
jQuery(function($) {
    $('#send').click(function() {

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

        // 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).


$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.