2013-11-26 98 views
0

作为REST调用的结果,我无法从对象XMLHttpRequest获取响应。我知道结果是在对象内部,因为当我返回结果时对象大小更大,但是我无法访问它们。这是我的javascript向服务器发出请求:无法从对象获取服务器响应XMLHttpRequest

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,但我有同样的问题,我可以没有得到任何回应。 在此先感谢。

+0

感谢jQuery,现在我不知道该怎么做内置的JavaScript类(并在原始类型中使用跨浏览器)。哈哈。 –

+0

您的浏览器是否记录其开发者工具中的任何错误(通常以“F12”,“Ctrl + Shift + J”或“Command + Shift + J”打开)?发出此请求的页面是否也来自'http:// localhost:8080 /'? –

回答

0

看起来你目前通过XMLHttpRequestActiveXObject本身displayMarkers作为值data

// ... 
    return displayMarkers(mypostrequest); 

来自服务器的响应将被存储在其responseText property,这将need to be parsed如果是JSON。

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

当然,假定发出此请求的页面也是​​。如果涉及另一起源(或在file://的情况下缺少起源),则more work is required to allow the request

+0

我想响应应该在responseText属性中,但是是空的。 – user3034457

相关问题