提前输入插件无法识别POST响应

时间:2019-05-07 21:55:16

标签: javascript arrays json spring-boot

我的Spring-boot POST端点返回的数据不适用于我正在使用的type ahead plugin。当我使用GET时可以使用。

此GET端点工作正常:

@RequestMapping(value = "/station", method = RequestMethod.GET)
public @ResponseBody List<Station> getstation() {
    List<Station> listStation = stationService.findAll();
    return listStation;
}

使用此javascript:

    $.get("/station", function(data) {
    console.log(data);
    $("[name='query']").typeahead({
        source: data,
        minLength: 3
    });
}, 'json');

返回的数据看起来像[{id:123,name:"ABC"}]

如果我尝试使用POST端点:

@RequestMapping(value = "/findstation", method = RequestMethod.POST)
public @ResponseBody List<Station> findstation(@RequestBody Station jsonSearchString) {
    List<Station> listStation = stationService.stationContaining(jsonSearchString.getName());
    return listStation;
}

使用javascript:

    $('#queryStation').keyup(function() {
    console.log("in change function statoion oc");
    var stationName = $(this).val();
    if(stationName.length==3){
        console.log("the length statement is true");
        ajax_search(stationName);
    }
});

function ajax_search(stationName){
    console.log("search function value " +stationName);
    var stationJson = '{ "name":"' +stationName+ '"}'
    $.ajax ({
        url: "/findstation",
        type: "POST",
        data: stationJson,
        dataType: "json",
        contentType: "application/json;",
        success: function(data){
        console.log("inside success handler");
            stationTypeahead(data);
        }
    });
}

function stationTypeahead(data){
    console.log(data);
    $('#queryStation').typeahead({
        source: data
    });
}

返回[{id:123, name:"LAX"}]之类的JSON-似乎不适用于该插件。 typeof data;返回对象。

如果我使用硬编码,例如data = [{"id":123,"name":"ABC"}],则该插件可以使用。

我很确定HTML可以与GET一起使用。

我想念什么?

更新

POST和GET的

Typeof均为object

1 个答案:

答案 0 :(得分:0)

将代码修改为:

function stationTypeahead(data){
    $("[name='query']").typeahead({
        source: data,
        minLength: 2
    });
}

HTML

<div class="col-md-5">
   <label class="control-label control-label-left">Station</label>
   <input type="text" class="form-control typeahead" name="query" id="queryStation" placeholder="Type Station" data-provide="typeahead" autcomplete="off">
</div>

我不知道为什么,但是当我使用选择器的jquery name属性作为typeahead plugin的目标时,它起作用了。从服务器返回的对象没有任何问题。