【问题标题】:Type-ahead plugin not recognizing POST response预输入插件无法识别 POST 响应
【发布时间】:2019-09-25 14:37:43
【问题描述】:

我的 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
    });
}

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

如果我硬编码,例如data = [{"id":123,"name":"ABC"}],这适用于插件。

我很确定 HTML 很好,因为它可以与 GET 一起使用。

我错过了什么?

更新

对于 POST 和 GET,Typeof 都是 object

【问题讨论】:

  • 您的回复内容类型是什么?如果您认为它需要一个字符串,为什么不直接对响应执行 JSON.stringify 然后传递给 typeahead。还有什么是“数据类型”;对于 GET 调用
  • @karthick 你的意思是在 POST 控制器上设置的响应内容类型?我发布了控制器。
  • 问题更像是您在响应标头中看到的内容类型?有时调用可能需要一个 json,而您可能将内容类型设置为文本。
  • 数据恢复正常。它是某种格式。只是不使用插件。
  • 看不到您向/findstation发出 POST 请求的任何地方

标签: javascript arrays json spring-boot


【解决方案1】:

修改代码为:

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 名称属性定位 typeahead plugin 时,它起作用了。服务器返回的对象没有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多