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

    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮