什么是Jquery的$ .getJSON的vanilla JS版本

osk*_*369 11 javascript jquery json

我需要构建一个项目来进入我正在申请的JS训练营.他们告诉我,我可能只使用vanilla JS,特别是不允许使用框架和Jquery.到目前为止,当我想从api中检索JSON文件时,我会说

$.getJSON(url, functionToPassJsonFileTo)
Run Code Online (Sandbox Code Playgroud)

用于JSON调用和

$.getJSON(url + "&callback?", functionToPassJsonPFileTo) 
Run Code Online (Sandbox Code Playgroud)

用于JSONP调用.我刚开始编程这个月所以请记住我不知道JSON或JSONP之间的区别,或者它们与这个名为ajax的东西有什么关系.请解释我如何在Vanilla Javascript中获得上述2行的内容.谢谢.

所以澄清一下,

function jsonp(uri){
    return new Promise(function(resolve, reject){
        var id = '_' + Math.round(10000 * Math.random())
        var callbackName = 'jsonp_callback_' + id
        window[callbackName] = function(data){
            delete window[callbackName]
            var ele = document.getElementById(id)
            ele.parentNode.removeChild(ele)
            resolve(data)
        }

        var src = uri + '&callback=' + callbackName
        var script = document.createElement('script')
        script.src = src
        script.id = id
        script.addEventListener('error', reject)
        (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)
    })
}
Run Code Online (Sandbox Code Playgroud)

会是JSONP的等价物吗?

Vic*_*ves 27

这是Vanilla JS版本$.getJSON:

var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();
Run Code Online (Sandbox Code Playgroud)

参考:http://youmightnotneedjquery.com/

对于JSONPSO已经有答案在这里

$.getJSON可以从使用GET HTTP请求的服务器加载JSON编码的数据.

  • 该链接是一个非常有用的资源,这里是逐行比较:http://youmightnotneedjquery.com/#json (2认同)

小智 7

ES6具有Fetch API,该API提供了一种全局fetch()方法,该方法提供了一种简单,逻辑的方式来跨网络异步获取资源。

比容易XMLHttpRequest

fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
    // Your code for handling the data you get from the API
})
.catch(function() {
    // This is where you run code if the server returns any errors
});
Run Code Online (Sandbox Code Playgroud)


小智 6

这是 Ajax 的普通 JS 版本

var $ajax = (function(){
    var that = {};
    that.send = function(url, options) {
        var on_success = options.onSuccess || function(){},
            on_error   = options.onError   || function(){},
            on_timeout = options.onTimeout || function(){},
            timeout    = options.timeout   || 10000; // ms

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                //console.log('responseText:' + xmlhttp.responseText);
                try {
                    var data = JSON.parse(xmlhttp.responseText);
                } catch(err) {
                    console.log(err.message + " in " + xmlhttp.responseText);
                    return;
                }
                on_success(data);
            }else{
                if(xmlhttp.readyState == 4){
                    on_error();
                }
            }
        };
        xmlhttp.timeout = timeout;
        xmlhttp.ontimeout = function () { 
            on_timeout();
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }
    return that;
})();
Run Code Online (Sandbox Code Playgroud)

例子:

$ajax.send("someUrl.com", {
    onSuccess: function(data){
        console.log("success",data);
    },
    onError: function(){
        console.log("Error");
    },
    onTimeout: function(){
        console.log("Timeout");
    },
    timeout: 10000
});
Run Code Online (Sandbox Code Playgroud)