LoginSignup
12
13

More than 5 years have passed since last update.

jQueryで連想配列をPOSTする

Last updated at Posted at 2014-10-18

やりたいこと

jQuery(Javascript)で連想配列を$.postで一気にPOSTしたい。

やったこと

sample.html
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
    <script>
    $(function(){


        //配列用意 []ではないので注意
        //{}とすることでオブジェクトになる
        var array = {};

        array['name']= "hoge";
        array['age'] = "30";

        //連想配列をjson文字列に変換
        //var json_str = JSON.stringify(array);
        //json文字列をjsonオブジェクトに変換
        //var json = $.parseJSON(json_str);

        //postで送る(第2引数はjson文字ではなくjsonオブジェクトである必要があるよう)
        //直接arrayでいける
        $.post("./res.php",array,function(res){
            alert(res);
        });

    });
    </script>
</head>
<body>
</body>
</html>

一度json文字列に変換してから、jsonオブジェクトにしている。たぶん1回の変換で済む方法があるのだろう。
{}とすることで、直接arrayを第2引数に入れれば良い。

POSTができてるかどうかは、res.phpで判断。print_r($_POST);とするだけ。

res.php
<?php

    print_r($_POST);
12
13
5

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
12
13