Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

jQueryなしでJSONデータを特定のURLにPOSTする

今回はjQuery無しでJSONデータを送る方法です。

実際のところ

今回はIFTTTのmakerに対し、JSONでパケットを叩きつける方法を考えます。

<html>
<body>
<script>
var postIFTTT = function () {
  xhr = new XMLHttpRequest();
  const appname = "{{YOUR_IFTTTAPP_NAME}}";
  const key     = "{{YOUR_KEY}}";
  const url     = "https://maker.ifttt.com/trigger/" + appname + "/with/key/" + key;
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-type", "application/json");
  xhr.onreadystatechange = function () { 
      if (xhr.readyState == 4 && xhr.status == 200) {
          var json = JSON.parse(xhr.responseText);
          console.log(json.email + ", " + json.password)
      }
  }
  var data = JSON.parse('{"value1" : "02/20/2017" , "value2" : "Some" , "value3" : "Thing" }');
  xhr.send(data);
}
</script>
<button onclick="postIFTTT()">GO_IFTTT</button>
</body>
</html>

GO_IFTTTのボタンを押すと、"maker"のトリガーが起動します。

参考もと

stackoverflow.com