9
10

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.

knockout.jsでJSONで通信する

Last updated at Posted at 2014-11-12

iOSとかでアプリ内でシリアル入力とかさせると違反になるおそれがあるので外部で入力させるようにするために作ったモックみたいなものを作ったのでそのサンプル。

knockout.jsを使用した理由は、社内コードを見たら使っていたのでっていうなんとなくの理由。

  • HTMLサンプル
index.html
<!doctype html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
    <script type="text/javascript">
      $(function() {
        function Campaign(data) {
          var self = this;
          
          self.ID = ko.observable(data.id);
          self.Name = ko.observable(data.name);
          self.UserID = ko.observable("");
          self.Code = ko.observable("");
          
          self.Save = function() {
            var data = {
              "id": self.ID(),
              "user_id": self.UserID(),
              "code": self.Code()
            };
            $.post("http://localhost:4567/", data, function(data) {
              console.log(data);      
            });
          }
        }
        
        function CampaignViewModel() {
          var self = this;
          
          self.Campaigns = ko.observableArray([]);
          
          $.getJSON("http://localhost:4567/", function(data) {
            var campaigns = $.map(data, function(item) { return new Campaign(item); });
            self.Campaigns(campaigns);
          });
        }
        
        ko.applyBindings(new CampaignViewModel());
      });
    </script>
  </head>
  <body>
    <div data-bind="foreach: Campaigns">
      <form method="post">
        <input type="hidden" data-bind="value: ID" />
        <label data-bind="value: Name"></label><br />
        <label>User ID</label><br />
        <input type="text" data-bind="value: UserID" /><br />
        <label>Code</label><br />
        <input type="text" data-bind="value: Code" /><br />
        <button data-bind="click: Save">Save</button>
      </form>
    </div>
  </body>
</html>
  • サーバコードサンプル
app.rb
require 'sinatra'
require 'json'


def get '/' do
  campaigns = [
    {
      id: 1,
      name: 'campaign 1',
    },
    {
      id: 2,
      name: 'campaign 2',
    },
  ]
  
  campaigns.to_json
end

def post '/' do
  {success: true}. to_json
end
9
10
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
9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?