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

    评论

报告相同问题?

悬赏问题

  • ¥30 频率分析法分析绘制奈奎斯特图、波特图
  • ¥15 弹出来一万个系统找不到指定的文件框框,怎么解决
  • ¥15 ADS生成的微带线为什么是蓝色空心的
  • ¥15 求一下解题思路,完全不懂
  • ¥15 tensorflow
  • ¥15 densenet网络结构中,特征以cat方式复用后是怎么进行误差回传的
  • ¥15 STM32G471芯片spi设置了8位,总是发送16位
  • ¥15 R语言并行计算beta-NTI中tree文件的类型
  • ¥15 如何解读marsbar导出的ROI数据?
  • ¥20 求友友协助弄一下基于STC89C52单片机的声光控制灯原理图