How to make a JSONP request from Javascript without JQuery?

后端 未结 12 1475
遇见更好的自我
遇见更好的自我 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条回答
  •  梦谈多话
    2020-11-22 17:56

    Please find below JavaScript example to make a JSONP call without JQuery:

    Also, you can refer my GitHub repository for reference.

    https://github.com/shedagemayur/JavaScriptCode/tree/master/jsonp

    window.onload = function(){
        var callbackMethod = 'callback_' + new Date().getTime();
    
        var script = document.createElement('script');
        script.src = 'https://jsonplaceholder.typicode.com/users/1?callback='+callbackMethod;
    
        document.body.appendChild(script);
    
        window[callbackMethod] = function(data){
            delete window[callbackMethod];
            document.body.removeChild(script);
            console.log(data);
        }
    }

提交回复
热议问题