Skip to content

Instantly share code, notes, and snippets.

@xgqfrms
Last active October 9, 2022 16:22
Show Gist options
  • Save xgqfrms/801601aec153b5a82364a6b48c0d4403 to your computer and use it in GitHub Desktop.
Save xgqfrms/801601aec153b5a82364a6b48c0d4403 to your computer and use it in GitHub Desktop.
JSONP

JSONP

<script src="https://cdn.xgqfrms.xyz/jsonp/users.json?callback=jsonpGlobalCallback"></script> bug ❌

image

Fetch API OK ✅

Text !== JSON

  /*
    err = TypeError: Failed to execute 'json' on 'Response': body stream already read at jsonp.html:40:16
    Uncaught (in promise) SyntaxError: Unexpected token 'j', "jsonpGloba"... is not valid JSON
  */
  const log = console.log;
  const app = document.querySelector(`#app`);
  log(`app =`, app);
  function jsonpGlobalCallback (arr) {
    log(`json =`, arr);
  }
  const url = `https://cdn.xgqfrms.xyz/jsonp/users.json?callback=jsonpGlobalCallback`;
  // const url = `https://cdn.xgqfrms.xyz/jsonp/users.json`;
  fetch(url, {
    // cors
  })
  .then(res => {
    log(`res =`, res);
    // read stream
    // log(`res =`, res, res.json());
    return res.text();
    // return res.json();
  })
  .then(jsonpText => {
    log(`jsonp text =`, jsonpText);
    app.innerHTML = ``;
    app.insertAdjacentHTML(`beforeend`, jsonpText);
  })
  .catch(err => {
    log(`err =`, err);
  });

image

image

https://www.cnblogs.com/xgqfrms/p/13424717.html

https://www.cnblogs.com/xgqfrms/tag/JSONP/