没有jquery的Ajax请求

时间:2015-09-16 17:33:26

标签: javascript ajax

如何获取data.json

  

{" KEY1":" VAL1"" KEY2":" val2的"}

带有功能

var getJSON = function (url) {
    var response = null;
    return (function () {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.responseType = 'json';
        xhr.onload = function () {
            response = xhr.status == 200 ? xhr.response : xhr.status;
        };
        xhr.send();
    })();
    return response;
};

代码

console.log(1);
console.log(getJSON('http://localhost/myproject/data.json'));
console.log(3);

给出

1
{"key1":"val1","key2":"val2"}
3

? 现在它给出了

1
null
3

谢谢

1 个答案:

答案 0 :(得分:-1)

使用承诺。

创建承诺(检查下面代码块中的第二行):

case 1: //if they hit OK
    $scope.modal_update.show();
    //PROCESSING DATA
    //do things with the data
    $scope.modal_update.hide();
    break;

使用 var map = L.map('map').setView([48.85, 2.35], 13); var stamenLayer = L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', { attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>.' }).addTo(map); function reqListener () { console.log(this.response); } var oReq = new XMLHttpRequest(); oReq.addEventListener("load", reqListener); oReq.open("GET", "http://dataratp.opendatasoft.com/api/records/1.0/download?dataset=liste-des-commerces-de-proximite-agrees-ratp&rows=100&format=geojson"); oReq.send(); L.geoJson(**WHAT TO INPUT HERE**).addTo(map); 语法来console.log

var getJSON = function (url) {
    return new Promise(function(){
        var response = null;
        return (function () {
            var xhr = new XMLHttpRequest();
            xhr.open('get', url, true);
            xhr.responseType = 'json';
            xhr.onload = function () {
                response = xhr.status == 200 ? xhr.response : xhr.status;
            };
            xhr.send();
        })();
        return response;
    })
};

打印1,3然后打印您的数据,同步ajax调用是异步。

供参考:http://eloquentjavascript.net/17_http.html 或官方文档:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise