island205 / Lu-Hire

陆金所大前端招聘!
61 stars 6 forks source link

隨便寫寫 #2

Open iwillwen opened 8 years ago

iwillwen commented 8 years ago
  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 commented 8 years ago

@iwillwen 👍👍👍