How to make a JSONP request from Javascript without JQuery?

后端 未结 12 1494
遇见更好的自我
遇见更好的自我 2020-11-22 17:27

Can I make a cross-domain JSONP request in JavaScript without using jQuery or other external library? I would like to use JavaScript itself and then parse the data and make

12条回答
  •  猫巷女王i
    2020-11-22 17:42

    Just pasting an ES6 version of sobstel's nice answer:

    send(someUrl + 'error?d=' + encodeURI(JSON.stringify(json)) + '&callback=c', 'c', 5)
        .then((json) => console.log(json))
        .catch((err) => console.log(err))
    
    function send(url, callback, timeout) {
        return new Promise((resolve, reject) => {
            let script = document.createElement('script')
            let timeout_trigger = window.setTimeout(() => {
                window[callback] = () => {}
                script.parentNode.removeChild(script)
                reject('No response')
            }, timeout * 1000)
    
            window[callback] = (data) => {
                window.clearTimeout(timeout_trigger)
                script.parentNode.removeChild(script)
                resolve(data)
            }
    
            script.type = 'text/javascript'
            script.async = true
            script.src = url
    
            document.getElementsByTagName('head')[0].appendChild(script)
        })
    }
    

提交回复
热议问题