weixin_33736649 2015-09-16 17:33 采纳率: 0%
浏览 28

没有jquery的Ajax请求[重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call" dir="ltr">How do I return the response from an asynchronous call?</a>
                            <span class="question-originals-answer-count">
                                (38 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2015-09-16 17:51:16Z" class="relativetime">4 years ago</span>.</div>
        </div>
    </aside>

How to get a data.json

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

with a function

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;
};

That the code

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

gives

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

? Now it gives

1
null
3

Thank you

</div>
  • 写回答

1条回答 默认 最新

  • weixin_33737134 2015-09-16 17:50
    关注

    Using promises.

    Create the promise (check the second line in the code block below):

    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;
        })
    };
    

    Use .then syntax to console.log

    console.log(1);
    getJSON('http://localhost/myproject/data.json').then(function(response){
        console.log(response);
        return;
    });
    console.log(3);
    

    It is gonna print 1,3 and then your data, synce the ajax call is async.

    For reference: http://eloquentjavascript.net/17_http.html or official docs: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同