Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

隨便寫寫 #2

Open
iwillwen opened this issue Mar 10, 2016 · 1 comment
Open

隨便寫寫 #2

iwillwen opened this issue Mar 10, 2016 · 1 comment

Comments

@iwillwen
Copy link

  1. Swiper 略
  2. Code here
const JSONP = (function() {
  const global = window

  const defaultOptions = Object.freeze({
    data: {},
    callback: (data) => {}
  })

  return (root, opts = defaultOptions) => {
    let url = root.trim().replace(/\?$/, '') + '?'

    const keys = Object.keys(opts.data)

    for (const key of keys) {
      url += `${safeEscape(key)}=${safeEscape(opts.data[key])}&`
    }

    const callbackName = `json${Math.random().toString(32).substr(2)}`

    global[callbackName] = function(data) {
      delete global[callbackName]
      opts.callback.call(JSONP, data)
    }

    url += `jsoncallback=${callbackName}`

    const script = document.createElement('script')
    script.src = url

    document.getElementsByTagName('body')[0].appendChild(script)
  }

  function safeEscape(str) {
    return encodeURIComponent(str.toString())
  }
})()

JSONP('http://api.flickr.com/services/feeds/photos_public.gne', {
  data: {
    tags: 'cat',
    tagmode: 'any',
    format: 'json'
  },
  callback(data) {
    console.log(data)
  }
})

3 . https://gist.github.com/iwillwen/aa3ea7d24633a2f3864d
another version: https://gist.github.com/iwillwen/b0ddaea384475d947540

@island205
Copy link
Owner

@iwillwen 👍👍👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants