Async XMLHttpRequest总是返回null但是同步工作正常

时间:2015-10-21 15:00:48

标签: javascript ajax rest asynchronous xmlhttprequest

我试图为自己的应用程序编写一个RestClient,但我无法理解一件事。

我的javascript对象有以下方法;

getRequest:function(path){
//Construct Url
var uri = self.baseUrl + path;
//Ajax Call : Dynamic

var xmlHttp = new XMLHttpRequest();

var apiResult;

var handleResponse = function(status, response) {
    apiResult = new ApiResult(JSON.parse(response), true, status); 
}

var handleError = function (status) {
    apiResult = new ApiResult("", false, status); 
}

var handleStateChange  =function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        handleResponse(xmlHttp.status, xmlHttp.responseText);
    }
    else{
        handleError(xmlHttp.status);
    }
}

xmlHttp.onreadystatechange = handleStateChange;

xmlHttp.open("GET", uri, true);
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.setRequestHeader("X-Authorization", self.token);

xmlHttp.send();

  return apiResult;

}

我就是这样一个非常简单的测试html;

<html>
<head>
    <script src="RestClient.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.js"></script>
    <script>
       $(document).ready(function() {
            var client = new RestClient("E3B55E5C-F086-4439-9268-217F9D0F5F71", "6C9FC7BD-453E-4D2A-905E-80269923D204");
        client.init();

        var result = client.getRequest("Api/Categories/GetAll");

        if (result.StatusCode == 200){
            jQuery.each(result.Data,function(index, element){
                $("#categorList").append("<li>"+ element.CategoryName+ "</li>");
            });
        }
        else{

        }

        console.log(result);
        console.log(client.getToken());
       });

    </script>
</head>
<body>
    <div>
        <span>Kategoriler</span>
        <div>
            <ul id="categorList">

            </ul>
        </div>
    </div>
</body>

如果我将呼叫设为异步,则列表不会加载,但如果我执行同步,则调用它可以吗?

它说syhc调用已被弃用。那么有人可以指导如何实现这种异步吗?

0 个答案:

没有答案