Jquery 它是如何工作的ResponseBody和它返回的内容

Jquery 它是如何工作的ResponseBody和它返回的内容,jquery,ajax,spring-boot,controller,Jquery,Ajax,Spring Boot,Controller,我有个问题。问题是@Reponsebody返回HTMLDOM,但我不想要这个。但是,如果我删除响应主体,它将在控制器中返回一个错误。 这是控制器: @GetMapping(value = "/isvoted") public @ResponseBody List<Boolean> isvoted() { Authentication auth= SecurityContextHolder.getContext().getAuthentication(); UserD

我有个问题。问题是@Reponsebody返回HTMLDOM,但我不想要这个。但是,如果我删除响应主体,它将在控制器中返回一个错误。 这是控制器:

@GetMapping(value = "/isvoted")
public @ResponseBody List<Boolean> isvoted() {

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());
    Long id = usuario.getId();

    List<Tapas> tapas = tapaService.findAllTapas();
    List<Boolean> listavotos = new ArrayList<Boolean>();

    for (Tapas tapa : tapas) {
        if (voteService.selectVoteByUserAndTapa(id, tapa.getId()) != null) {
            listavotos.add(true);
        }else {
            listavotos.add(false);
        }
    }
    return listavotos;
@Controller
要继续,当文档准备好时,它被称为ajax get请求,用于kwnow如果有投票,如果有投票,它将返回布尔值列表(响应),它从控制器ISNOTED获取,但也返回reponsebody(html正文),但我不希望这样。我希望控制器只返回列表给kwnow,如果它投票了一个元素,如果它投票了一个css样式,如果没有投票,则有另一个样式。非常感谢你的帮助。如果你需要更多刚刚发布的信息,我会澄清

完整控制器(不是restcontroller):

公共类VoteController{

@Autowired
private IVoteService voteService;

@Autowired
private IUsuarioService usuarioService;

@Autowired
private ITapasService tapaService;

private final Logger log = LoggerFactory.getLogger(getClass());

@GetMapping(value = "/isvoted")
@ResponseBody
public List<Boolean> isvoted(@RequestBody List<Boolean> listavotos) {

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());
    Long id = usuario.getId();

    List<Tapas> tapas = tapaService.findAllTapas();
    listavotos = new ArrayList<Boolean>();

    for (Tapas tapa : tapas) {
        if (voteService.selectVoteByUserAndTapa(id, tapa.getId()) != null) {
            listavotos.add(true);
        }else {
            listavotos.add(false);
        }
    }
    return listavotos;

}

@PostMapping(value = "/votecreate")
public String guardar(@Valid Vote vote, BindingResult result, Model model,
        @RequestParam(name = "tapa", required = true) Tapas tapa,
        RedirectAttributes flash, SessionStatus status) {

    if (result.hasErrors()) {
        List<ObjectError> errors = result.getAllErrors();
        for(ObjectError error : errors) {
            System.out.println("This is the error: " +error);
        }
        return "redirect:/home";
    }

    //String mensajeFlash = (vote.getId() != null) ? "voto quitado con con exito" : "votado con exito!";

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());

    //Tapas tapa = tapaService.findTapaById(Long.parseLong(tapaid));

    vote.setTapa(tapa);
    vote.setUsuario(usuario);

    voteService.save(vote);
    status.setComplete();
    //flash.addFlashAttribute("success", mensajeFlash);

    return "redirect:/home";
}

@GetMapping(value = "/votedelete/{tapaId}")
public String eliminar(@PathVariable(value = "tapaId") Long tapaId, RedirectAttributes flash) {

    //Tapas tapa = tapaService.findTapaById(tapaId);

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());
    Long userId = usuario.getId();
    log.debug("Usuario id:", userId);

    if (userId != null && tapaId != null) {

        Vote vote = voteService.selectVoteByUserAndTapa(userId, tapaId);
        log.debug("vote:", vote.getId());
        voteService.delete(vote.getId());
        flash.addFlashAttribute("success", "Voto eliminado con exito");

        return "redirect:/home/";
    }

    flash.addFlashAttribute("error", "El bar no existe en la base de datos");
    return "redirect:/bares/";
}
@Autowired
私人IVoteService voteService;
@自动连线
私人服务;
@自动连线
私人电话服务;
私有最终记录器log=LoggerFactory.getLogger(getClass());
@GetMapping(value=“/isvoted”)
@应答器
公共列表已投票(@RequestBody List listavotos){
Authentication auth=SecurityContextHolder.getContext().getAuthentication();
UserDetails UserDetails=(UserDetails)auth.getPrincipal();
Usuario-Usuario=(Usuario)usuarioService.findByUsername(userDetails.getUsername());
Long id=usuario.getId();
List tapas=tapaService.findAllTapas();
listavotos=newarraylist();
用于(小吃小吃:小吃){
if(voteService.SelectVoteBySerandTapa(id,tapa.getId())!=null){
listavotos.add(true);
}否则{
listavotos.add(false);
}
}
返回listavotos;
}
@后期映射(value=“/votecreate”)
公共字符串guardar(@Valid Vote Vote,BindingResult,Model Model,
@RequestParam(name=“tapa”,required=true)Tapas tapa,
重定向属性(闪存、会话状态){
if(result.hasErrors()){
List errors=result.getAllErrors();
for(ObjectError错误:错误){
System.out.println(“这是错误:“+错误”);
}
返回“重定向:/home”;
}
//字符串mensajeFlash=(vote.getId()!=null)?“voto quitado con exito”:“votado con exito!”;
Authentication auth=SecurityContextHolder.getContext().getAuthentication();
UserDetails UserDetails=(UserDetails)auth.getPrincipal();
Usuario-Usuario=(Usuario)usuarioService.findByUsername(userDetails.getUsername());
//Tapas tapa=tapaService.findTapaById(Long.parseLong(tapaid));
投票:setTapa(tapa);
投票:setUsuario(usuario);
voteService.save(投票);
status.setComplete();
//addFlashAttribute(“成功”,mensajeFlash);
返回“重定向:/home”;
}
@GetMapping(value=“/votedelete/{tapaId}”)
公共字符串eliminar(@PathVariable(value=“tapaId”)长tapaId,重定向属性flash){
//Tapas tapa=tapaService.findTapaById(tapaId);
Authentication auth=SecurityContextHolder.getContext().getAuthentication();
UserDetails UserDetails=(UserDetails)auth.getPrincipal();
Usuario-Usuario=(Usuario)usuarioService.findByUsername(userDetails.getUsername());
Long userId=usuario.getId();
调试(“Usuario id:”,userId);
if(userId!=null&&tapaId!=null){
投票表决=voteService。选择VoteBySerandTapa(用户ID,tapaId);
log.debug(“投票:,投票.getId());
delete(vote.getId());
addFlashAttribute(“成功”,“Voto eliminado con exito”);
返回“重定向:/home/”;
}
flash.addFlashAttribute(“错误”,“基准数据中不存在El bar”);
返回“重定向:/bares/”;
}

}

问题是,当在映射/isvote上的控制器中时,当用户登录(它获取身份验证详细信息)并且存在TAPA(获取TAPA的id)时,可以执行jQuery,因为可以成功地查询存储库,但当用户未登录时,它返回一个thymeleaf布局字符串,因此,我只添加了一个条件,以了解控制器的返回是否为字符串(thymelead的DOM),而不是bool列表。it控制台记录一条消息,表明用户未通过身份验证,因此没有显示结果的选项(Boolean列表)


问题是,当在mapping/IsVote上的控制器中时,当用户登录(它获取身份验证详细信息)并且存在TAPA(获取TAPA的id)时,可以执行jQuery,因为可以成功地查询存储库,但当用户未登录时,它会返回thymeleaf布局的字符串,因此,我只添加了一个条件,以了解控制器的返回是否为字符串(thymelead的DOM),而不是bool列表。it控制台记录一条消息,表明用户未通过身份验证,因此没有显示结果的选项(Boolean列表)


你能添加整个控制器类吗?试着在ajax调用中添加这一行,
数据类型:“json”
@Ismaelits就像在应用程序上我没有登录时,auth user参数传递到控制器上的vote.repository,它返回HTML DOM,因为没有auth user来获取id,但我创建了一个用户,并记录了它的运行情况,然后返回一个boolen列表。我该怎么办?如果在没有用户日志的情况下不返回HTML,您可以添加整个控制器类吗?尝试在ajax调用中添加这一行,
数据类型:“json”,
@Ismaelits,就像在应用程序“我没有登录”上一样,auth user参数传递到控制器上的vote.repository,它返回HTML DOM,因为没有用于获取id的auth user,但我创建并记录了一个用户,它似乎可以工作,并返回一个boolen列表。我该怎么办?如果没有用户登录,则返回HTML
@Autowired
private IVoteService voteService;

@Autowired
private IUsuarioService usuarioService;

@Autowired
private ITapasService tapaService;

private final Logger log = LoggerFactory.getLogger(getClass());

@GetMapping(value = "/isvoted")
@ResponseBody
public List<Boolean> isvoted(@RequestBody List<Boolean> listavotos) {

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());
    Long id = usuario.getId();

    List<Tapas> tapas = tapaService.findAllTapas();
    listavotos = new ArrayList<Boolean>();

    for (Tapas tapa : tapas) {
        if (voteService.selectVoteByUserAndTapa(id, tapa.getId()) != null) {
            listavotos.add(true);
        }else {
            listavotos.add(false);
        }
    }
    return listavotos;

}

@PostMapping(value = "/votecreate")
public String guardar(@Valid Vote vote, BindingResult result, Model model,
        @RequestParam(name = "tapa", required = true) Tapas tapa,
        RedirectAttributes flash, SessionStatus status) {

    if (result.hasErrors()) {
        List<ObjectError> errors = result.getAllErrors();
        for(ObjectError error : errors) {
            System.out.println("This is the error: " +error);
        }
        return "redirect:/home";
    }

    //String mensajeFlash = (vote.getId() != null) ? "voto quitado con con exito" : "votado con exito!";

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());

    //Tapas tapa = tapaService.findTapaById(Long.parseLong(tapaid));

    vote.setTapa(tapa);
    vote.setUsuario(usuario);

    voteService.save(vote);
    status.setComplete();
    //flash.addFlashAttribute("success", mensajeFlash);

    return "redirect:/home";
}

@GetMapping(value = "/votedelete/{tapaId}")
public String eliminar(@PathVariable(value = "tapaId") Long tapaId, RedirectAttributes flash) {

    //Tapas tapa = tapaService.findTapaById(tapaId);

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());
    Long userId = usuario.getId();
    log.debug("Usuario id:", userId);

    if (userId != null && tapaId != null) {

        Vote vote = voteService.selectVoteByUserAndTapa(userId, tapaId);
        log.debug("vote:", vote.getId());
        voteService.delete(vote.getId());
        flash.addFlashAttribute("success", "Voto eliminado con exito");

        return "redirect:/home/";
    }

    flash.addFlashAttribute("error", "El bar no existe en la base de datos");
    return "redirect:/bares/";
}
if (result === undefined || result.length == 0)
    console.log("no hay votos");
else if (typeof(result) == "string")
    console.log("you are not logger, you should be logged to see the VOTES");
else
    for (var voto of result) {
        console.log(result);

        if (voto === true) {
            full.prop('disabled', true);
            console.log(voto);
        } else {
            full.prop('disabled', false);
            console.log(voto);
        }
    }