LoginSignup
2
0

More than 5 years have passed since last update.

ブラウザからjsonをpostして結果をファイルでダウンロードするスクリプト

Last updated at Posted at 2017-09-09
function textSave (name, text) {
  var blob = new Blob([text], {type: 'text/plain'})
  var link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = name || 'text-save-data.txt'
  link.click()
}

function sendinfo (url, data, fileName, callback) {
  var xhr = new XMLHttpRequest()
  xhr.onload = function () {
    if (this.status === 200) {
      textSave(fileName, this.responseText)
      callback && callback()
    } else {
      console.log(this.status, this.responseText)
    }
  }
  xhr.open('POST', url)
  xhr.withCredentials = true
  xhr.setRequestHeader('Content-Type', 'application/json')
  xhr.send(JSON.stringify(data))
}

sendinfo('http://echo.jpillora.com/', {aaa: 'aaa1', msg: 'めっせーじだょ'})

一旦、こちらにhttp://echo.jpillora.com/移動してから、chromeブラウザのコンソールに打てば実行できます(CORSがあるから移動は仕方ない)

npmでechoサーバでも建ててテストしようかなぁと思ったら、作者の人がechoサーバ公開してくれていたから、そのまま使わせてもらった。

https://www.npmjs.com/package/echo-server

会社等で使う場合は、自分でechoサーバ建てたほうが情報漏えいとか気にせず使えると思います。

余談ですが、コーディングスタイルはStandardStyleを使ってみました。意外とセミコロンが無い生活も快適ですね。
JavaScriptのStandardStyleを使って手軽にフォーマットする方法

2
0
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
2
0