无法从对象XMLHttpRequest获取服务器响应

时间:2013-11-26 00:44:39

标签: java javascript ajax rest

由于REST调用,我无法从对象XMLHttpRequest获得响应。我知道结果在对象内部,因为当我有结果返回时对象大小更大,但无论如何我都无法访问它们。这是我对服务器的javascript请求:

function getMarkersByCategory(category) {
      var urlServer = 'http://localhost:8080/api/mapit/getcategory';
      return loadContent(urlServer,category);
}

function loadContent(url, category) {
     var mypostrequest = new ajaxRequest();
     mypostrequest.onreadystatechange = function() {
     if (mypostrequest.readyState == 4) {
         if (mypostrequest.status == 200 || window.location.href.indexOf("http") == -1)     {
              return displayMarkers(mypostrequest);
          }

     else {
         alert("An error has occured making the request");
          }
     }
     }

     var parameters = "?category=" + category ;
     mypostrequest.open("GET", url + parameters , true);
     mypostrequest.send(null);
}

function ajaxRequest() {
    var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to   check for in IE
    if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
        for (var i = 0; i < activexmodes.length; i++) {
            try {
                 return new ActiveXObject(activexmodes[i]);
            }
             catch (e) {
                //suppress error
            }
        }

    }
    else if (window.XMLHttpRequest) // if Mozilla, Safari etc
       return new XMLHttpRequest();
    else
       return false;
    }

function displayMarkers(data) {
    alert(data);
    var jsonContent = data // I can´t find any property of the object with the response
}

最后这是我的Java Web服务的响应:

@GET 
@Produces("text/plain")//I have tried with ("application/json") too
@Path("/getcategory")
public String getByCategory(@QueryParam("category") String category) {
    List<MapItBean> list = mapItPointDao.getMapItPointsByCategory(category);
    String result = MapItBeanHelper.jsonizeMapitList(list);
    System.out.println(result);
    return result;
}

我尝试使用jquery,但我有同样的问题,我无法得到任何回应。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您似乎正在将XMLHttpRequestActiveXObject本身传递给displayMarkers作为data的值。

// ...
    return displayMarkers(mypostrequest);

来自服务器的响应将存储在responseText property中,如果它是JSON,则会need to be parsed

// ...
    return displayMarkers(JSON.parse(mypostrequest.responseText));

当然,这假定发出此请求的页面也在http://localhost:8080/上。如果涉及其他来源(或file://),则为more work is required to allow the request