Skip to content

Instantly share code, notes, and snippets.

@xgqfrms-GitHub
Last active July 5, 2017 06:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xgqfrms-GitHub/68af127cb3ec33587ee5bffe9810fb1b to your computer and use it in GitHub Desktop.
Save xgqfrms-GitHub/68af127cb3ec33587ee5bffe9810fb1b to your computer and use it in GitHub Desktop.
AJAX & XMLHttpRequest & Fetch & Worker & jquery ajax
@xgqfrms-GitHub
Copy link
Author

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Apr 13, 2017

MDN Fetch with init then Request example

https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch

https://mdn.github.io/fetch-examples/fetch-with-init-then-request/

https://github.com/mdn/fetch-examples/tree/gh-pages/fetch-with-init-then-request

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">

    <title>Fetch with init then Request example</title>

    <link rel="stylesheet" href="">
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>

  <body>
    <h1>Fetch with init then Request example</h1>
    <img src="">

  </body>
  <script>
    var myImage = document.querySelector('img');

    var myHeaders = new Headers();
    myHeaders.append('Content-Type', 'image/jpeg');

    var myInit = {
      method: 'GET',
      headers: myHeaders,
      mode: 'cors',
      cache: 'default'
    };

    var myRequest = new Request('flowers.jpg');

    fetch(myRequest, myInit)
    .then(function(response) { return response.blob(); })
    .then(function(blob) {
      var objectURL = URL.createObjectURL(blob);
      myImage.src = objectURL;
    });

  </script>
</html>

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Apr 13, 2017

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Apr 13, 2017

URL

https://developer.mozilla.org/zh-CN/docs/Web/API/URL

https://developer.mozilla.org/zh-CN/docs/Web/API/URL/URL

HTMLHyperlinkElementUtils.toString() 方法返回一个包含整个URL的 USVString 。
它是HTMLHyperlinkElementUtils.href 的一个只读版本。

https://developer.mozilla.org/zh-CN/docs/Web/API/URLUtils/toString

HTMLHyperlinkElementUtils.href 属性是一个包含整个URL的 USVString。

https://developer.mozilla.org/zh-CN/docs/Web/API/URLUtils/href

Bolb

一个 Blob对象表示一个不可变的, 原始数据的类似文件对象。
Blob表示的数据不一定是一个JavaScript原生格式。
File 接口基于Blob,继承 blob功能并将其扩展为支持用户系统上的文件。

https://developer.mozilla.org/zh-CN/docs/Web/API/Blob

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Apr 13, 2017

在web应用中使用文件

使用在HTML5中添加到DOM的File API,现在可以让Web内容要求用户选择本地文件,然后读取这些文件的内容。
此选择可以通过使用HTML 元素或通过拖放来完成。

https://developer.mozilla.org/zh-CN/docs/Using_files_from_web_applications

FileReader

https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader

FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,
使用 File 或 Blob 对象指定要读取的文件或数据。

@xgqfrms-GitHub
Copy link
Author

bugs (cdn url & cors)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>fetch</title>
</head>
<body>
    <div>
        <h1>fetch demo</h1>
        <img src="" alt="img" title="img" />
    </div>
    <script>
        let myImage = document.querySelector('img');
        let myHeaders = new Headers();
        // myHeaders.append('Content-Type', 'image/jpeg');
        myHeaders.append('Content-Type', 'image/png');
        // https://cdn.xgqfrms.xyz/json/cats.json
        // https://cdn.xgqfrms.xyz/logo/icon.png
        let myInit = {
            method: 'GET',
            headers: myHeaders,
            mode: 'no-cors',
            cache: 'default'
        };
        // mode: 'cors',
        // Access-Control-Allow-Origin
        /*
        fetch.html:1 Fetch API cannot load https://cdn.xgqfrms.xyz/logo/icon.png. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled
        */

        // let myRequest = new Request('https://cdn.xgqfrms.xyz/logo/icon.png');
        let myRequest = new Request('icon.png');

        fetch(myRequest,myInit).then(
            function(response) {
                // alert("OK");
                console.log("OK");
                console.log(response);
                // console.log(response.blob());
                // response.blob()
                return response.blob();
            }
        ).then(
            function(blob) {
                console.log(blob);
                let cdnURL = "https://cdn.xgqfrms.xyz/";
                console.log(blob);
                let objectURL = URL.createObjectURL(blob);
                console.log(objectURL);
                let newobjectURL = `${cdnURL}${blob}`
                console.log(newobjectURL);
                myImage.src = objectURL;
                console.log(myImage.src);
            }
        );
    </script>
</body>
</html>

@xgqfrms-GitHub
Copy link
Author

icon

blob to string

http://stackoverflow.com/a/23024613
https://stackoverflow.com/questions/23024460/javascript-i-created-a-blob-from-a-string-how-do-i-get-the-string-back-out

function blobToString(b) {
    var u, x;
    u = URL.createObjectURL(b);
    x = new XMLHttpRequest();
    x.open('GET', u, false); // although sync, you're not fetching over internet
    x.send();
    URL.revokeObjectURL(u);
    return x.responseText;
}
    var b = new Blob(['hello world']);
    blobToString(b); // "hello world"
    var img = new Blob(["https://cdn.xgqfrms.xyz/logo/icon.png"]);
    let newImg = blobToString(img);
    console.log(newImg);

http://qnimate.com/an-introduction-to-javascript-blobs-and-file-interface/

@xgqfrms-GitHub
Copy link
Author

new Blob

http://www.javascripture.com/Blob

Creates a new Blob.
The elements of blobParts must be of the types ArrayBuffer, ArrayBufferView, Blob, or String.
If ending is set to 'native', the line endings in the blob will be converted to the system line endings,
such as '\r\n' for Windows or '\n' for Mac.

new Blob(blobParts : Array, [blobPropertyBag : Object]) : Blob
blobPropertyBag : {
    type    String  A valid mime type such as 'text/plain'
    endings String  Must be either 'transparent' or 'native'
}

new-bolb

var blob = new Blob(["http://www.javascripture.com/Blob"], {type: "text/json"});

console.log(blob);
console.log(blob.size);
console.log(blob.type);

@xgqfrms-GitHub
Copy link
Author

How-to-convert-ArrayBuffer-to-and-from-String

https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String

// suppose buf contains the bytes [0x02, 0x01, 0x03, 0x07]
// notice the multibyte values respect the hardware endianess, which is little-endian in x86
var bufView = new Uint16Array(buf);
if (bufView[0]===258) {   // 258 === 0x0102
  console.log("ok");
}
bufView[0] = 255;    // buf now contains the bytes [0xFF, 0x00, 0x03, 0x07]
bufView[0] = 0xff05; // buf now contains the bytes [0x05, 0xFF, 0x03, 0x07]
bufView[1] = 0x0210; // buf now contains the bytes [0x05, 0xFF, 0x10, 0x02]
function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function str2ab(str) {
  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint16Array(buf);
  for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

@xgqfrms-GitHub
Copy link
Author

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented May 16, 2017

fetch

https://gist.github.com/xgqfrms-GitHub/b44ba9049575654e36e3032c58576931

<script>
    fetch('https://github-cloud.s3.amazonaws.com/', {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            "title":   "Add a blogpost about Angular2",
            "dueDate": "2015-05-23T18:25:43.511Z",
            "done": false
        })
    }).then(function(response) {
            return response.json()
    }).then(function(json) {
            console.log('parsed json: ', json)
    }).catch(function(error) {
          console.log('parsing failed: ', error)
    });




    fetch('https://cdn.xgqfrms.xyz/json/cats.json', {
        method: 'get',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    }).then(function(response) {
            return response.json()
    }).then(function(json) {
            console.log('parsed json: ', json)
    }).catch(function(error) {
          console.log('parsing failed: ', error)
    });
</script>

@xgqfrms-GitHub
Copy link
Author

React JSON-Server

json-server

$ npm i -g json-server

$ npm i -D json-server

faker.js

https://www.npmjs.com/package/faker

$ npm i -D faker

yarn

$ yarn add -D json-server

$ yarn add -D faker

@xgqfrms-GitHub
Copy link
Author

let myImage = document.querySelector('img');

let myHeaders = new Headers();
myHeaders.append('Content-Type', 'image/png');

const myInit = {
    method: 'GET',
    headers: myHeaders,
    mode: 'cors',
    cache: 'default'
};

let myRequest = new Request('https://cdn.xgqfrms.xyz/logo/icon.png');

fetch(myRequest, myInit)
.then(function(response) {
    return response.blob();
})
.then(function(blob) {
    var objectURL = URL.createObjectURL(blob);
    myImage.src = objectURL;
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment