helloxielan 2015-06-09 19:01 采纳率: 0%
浏览 21

Spring MVC和Ajax错误406

I'm trying to run an ajax method with spring MVC, but I'm getting the error 406: "The resource identified by this request is only capable of generating responses with characteristics not acceptable According to the request" accept "headers"

Controller:

@Transactional
@Controller("user")
@SessionAttributes("user")
public class HomeController {
@Autowired
private UserDAO daoUser;
@Autowired
private EnterpriseDAO daoEnterprise;
@Autowired
private FuncDAO daoFunc;
@Autowired
private LastPeriodDAO daoLastPeriod;

@RequestMapping("/")
public String index() {
    return "redirect:menu";
}

@RequestMapping(value = "/menu", method = RequestMethod.GET)
public ModelAndView menu(@ModelAttribute("user") User user, Enterprise enterprise) {
    ModelAndView mav = new ModelAndView("user/menu");

    Func func = daoFunc.getFunc(user);
    mav.addObject("func", func);
    mav.addObject("enterprise", enterprise);
    mav.addObject("enterpriseList", daoEmpresa.listEnterprise(func));

    return mav;

}
@RequestMapping(value = "/dynamicMenu", method = RequestMethod.POST)
public @ResponseBody List<LastPeriod> dynamicOption(@ModelAttribute("enterprise") Enterprise enterprise) {

    System.out.println(enterprise.getCnpj());
    List<LastPeriod> options = daoLastPeriod.getLastPeriod(enterprise);

    System.out.println(options.size());

    return options;
}

Request ajax:

$(document).ready(function() {
function enterpriseSelectChange() {
    var enterprise= $(this).serialize();

    $.ajax({
        type: 'POST',
        url: 'dynamicMenu',
        data: enterprise,
    })

    .done(function(data) {
        console.log("success");
        console.log(data)
    })
    .fail(function() {
        console.log("error");
    });
}
$("#cnpj").change(enterpriseSelectChange);

});

Form:

                <form:form modelAttribute="enterprise" commandName="enterprise" class="form-horizontal" method="POST">
                <fieldset>
                    <legend>Olá, ${func.name}</legend>

                    <!-- Select enterprise -->
                    <div class="form-group">
                        <label for="enterprise">Enterprise</label>

                        <form:select path="cnpj" class="form-control">
                            <form:option value="0" label=" Select"/>
                            <form:options items="${enterpriseList}" itemValue="cnpj"/>
                        </form:select>
                    </div>
                </form:form>

Please, anyone have any solutions ?

EDIT

Included controller and form

  • 写回答

4条回答 默认 最新

  • weixin_33720078 2015-06-09 19:19
    关注

    406 means "not acceptable". Try to add header content-type when sending the request:

    $.ajax({
        type: 'POST',
        headers:{
            'Content-type:application/x-www-form-urlencoded'
        },
        url: 'dynamicMenu',
        data: enterprise,
    })
    
    .done(function(data) {
        console.log("success");
        console.log(data)
    })
    .fail(function() {
        console.log("error");
    });
    

    application/x-www-form-urlencoded

    评论
  • weixin_33724059 2015-06-10 01:11
    关注

    Essentially, the error message is saying that the server cannot generate a response type that is acceptable to your AJAX call. The server is expecting your "Accept" header to contain a type that it can generate response in.

    Try setting the "Accept" header in your AJAX call:

    $.ajax({
        type: 'POST',
        headers:{
            'Accept:application/json'
        },
        ...
    })
    

    Note the difference between the headers

    1. "Content-Type" --> request content is of this type/format
    2. "Accept" --> I will accept a response in this type/format

    The other comment asks you to set your content-type but the error message you posted seems to indicate that you need to set the "Accept" header.

    评论
  • 程序go 2015-06-10 12:01
    关注

    So here is your problem,

    You need to return jsonObject but actually you are returning the List of LastPeriod Object i.e. List<LastPeriod>.

    So you need to change in method,

    @RequestMapping(value = "/dynamicMenu", method = RequestMethod.POST)
    public @ResponseBody List<LastPeriod> dynamicOption(@ModelAttribute("enterprise") Enterprise enterprise) {
    
        List<LastPeriod> options = daoLastPeriod.getLastPeriod(enterprise);
        JSONArray jsonArray = new JSONArray();
        for(LastPeriod lastPeriod: options){
            JSONObject jsonObject = new JSONObject();
            //Here put data in jsonObject from lastPeriod like 
            jsonObject.put("name", "populate field from lastPeriod");
            jsonArray.add(jsonObject);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", jsonArray);
        return jsonObject.toJSONString();
    }
    

    Now you will get ajax response as array like.

    $.ajax({
        type: 'POST',
        url: 'dynamicMenu',
        data: enterprise,
        success: function(resp){
            var parseJson = JSON.parse(resp);
            console.log(parseJson.data);
        }
    });
    
    评论
  • weixin_33734785 2015-06-11 12:57
    关注

    First thank you for your help.

    I had a problem in the spring configuration, which was configured an JsonViewResolver , configureContentNegotiation , contentNegotiatingViewResolver . I think I had to specify a return on the controller.

    As just I need a JSON disregarded those settings and is now working.

    Personal , first thank you for your help.

    I had a problem in the spring configuration, which was configured an JsonViewResolver , configureContentNegotiation , contentNegotiatingViewResolver . I think I had to specify a return on the controller.

    As just I need a JSON disregarded those settings and is now working.

    I also changed my method because it does not need to receive an object , only one id. Therefore it looked like this:

    @RequestMapping(value = "/dynamicMenu/{cnpj}", method = RequestMethod.GET)
    public @ResponseBody List<UltimoPeriodoAberto> DynamicOptions(@PathVariable final String cnpj) {
    
        return daoLastPeriod.getLastPeriod(new Enterprise(cnpj));
    }
    

    Request ajax:

    var cnpj = $(this).val();
        $.ajax({
            type: 'get',
            url: 'http://localhost:8080/myincome/dynamicMenu/' + cnpj,
        })
        .done(function(data) {
            console.log("success");
    
            console.log(data[0]);
    
            for ( var i = 0; i < data.length; i++) {
                console.log(data[i].description);
            }
    
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            console.log("The following error occured: " + textStatus, errorThrown);
        });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 存储过程或函数中的结果集类型变量如何使用。
  • ¥80 关于海信电视聚好看安装应用的问题
  • ¥15 vue引入sdk后的回调问题
  • ¥15 求一个智能家居控制的代码
  • ¥15 ad软件 pcb布线pcb规则约束编辑器where the object matpcb布线pcb规则约束编辑器where the object matchs怎么没有+15v只有no net
  • ¥15 虚拟机vmnet8 nat模式可以ping通主机,主机也能ping通虚拟机,但是vmnet8一直未识别怎么解决,其次诊断结果就是默认网关不可用
  • ¥20 求各位能用我能理解的话回答超级简单的一些问题
  • ¥15 yolov5双目识别输出坐标代码报错
  • ¥15 这个代码有什么语法错误
  • ¥15 给予STM32按键中断与串口通信