从GeoServer检索图层名称的AJAX回调失败,出现断言错误

时间:2016-02-22 13:25:03

标签: javascript jquery ajax openlayers-3 geoserver

我正在写一些东西来从我的GeoServer获取所有图层名称。这是我的代码:

function getData() {
    return $.ajax({
        url: "http://localhost:8080/geoserver/ows?service=wms&version=1.1.0&request=GetCapabilities",
        type: 'GET'
    });
}

function onComplete(data) {

    var parser = new ol.format.WMSCapabilities();
    var result = parser.read(data.responseText);

    var layersArray = result.Capability.Layer.Layer;
    layersNameArray = [];

    for(i=0;i<layersArray.length;i++){
        layersNameArray.push(layersArray[i].Name)
    }

    return layersNameArray
}

getData().done(onComplete)

我远非异步调用的专家,但我认为这个应该有效。如果我将getData()结果存入变量并逐行运行onComplete()函数,则代码可以正常工作。但是当我使用getData().done(onComplete)运行代码时,它始终会在var result = parser.read(data.responseText);Assertion error: Failure处失败。

知道为什么这不起作用吗?

修改

此代码有效,但不返回任何内容。我希望函数输出layersNameArray变量。我该怎么办?

function getData() {
    $.ajax({
        url: "http://localhost:8080/geoserver/ows?service=wms&version=1.1.0&request=GetCapabilities",
        type: 'GET',
        success: function(response) {
            var parser = new ol.format.WMSCapabilities();
            var result = parser.read(response);

            var layersArray = result.Capability.Layer.Layer;
            layersNameArray = [];

            for(i=0;i<layersArray.length;i++){
                layersNameArray.push(layersArray[i].Name)
            }

            return layersNameArray
        }
    });
}

1 个答案:

答案 0 :(得分:2)

您可以使用Jquery回调功能

以这种方式调用你的函数,

getData(function(responsefromAjax){
   alert('the response from ajax is :' +responsefromAjax);
  // what ever logic that needs to run using this ajax data
 });

以这种方式改变你的方法。

function getData(callback) { // passing the function as parameter
    $.ajax({
        url: "http://localhost:8080/geoserver/ows?service=wms&version=1.1.0&request=GetCapabilities",
        type: 'GET',
        success: function(response) {
            var parser = new ol.format.WMSCapabilities();
            var result = parser.read(response);

            var layersArray = result.Capability.Layer.Layer;
            layersNameArray = [];

            for(i=0;i<layersArray.length;i++){
                layersNameArray.push(layersArray[i].Name)
            }

            callback(layersNameArray); //this will execute your function defined during the function call. As you have passed the function as parameter.
        }
    });
}

如果有帮助,请告诉我