猿问

如何从控制器发送返回的布尔结果以在 spring mvc 中查看

我想将控制器方法的返回值(即标志)发送到我的视图中,并且在视图中我需要根据此标志显示一条警报消息。这是我的控制器代码


@RequestMapping(value = "/testing", method = RequestMethod.POST)

public Boolean testing(@RequestBody String value, HttpSession session, String username, ModelMap modelMap, HttpServletRequest request) throws Exception {

  Boolean flag = false;

  User userData = (User) session.getAttribute("MEMBER");

  for (OrgData org: orgDataRepository.findAll()) {

    if (m.getValue() != null) {

      sourceAccessToken = (String) m.getValue();

      flag = true;

    } else {

      System.out.println("Refresh token is expired");

      flag = false;

    }

  }

  return flag;

}

我的视图代码如下所示


let btnVal = document.querySelectorAll('.test-btn');

for (let i = 0; i < btnVal.length; i++) {

  let btns = btnVal[i];

  btns.onclick = function() {

    var selchbox = getSelectedChbox(this.form); // gets the array returned by getSelectedChbox()

    if (selchbox.length == 1) {

      //document.write("check check"+selchbox);

      $.ajax({

        type: "POST",

        url: "/testing",

        dataType: "JSON",

        contentType: "application/json; charset=utf-8",

        data: JSON.stringify(selchbox),

        cache: false,

        success: function(data) {

          alert("SUCCESS!!!");

        },

        error: function(args) {

          /* alert("Error on ajax post");

          console.log("Error"+args); */

        }


      });

    } else {

      alert("Please select only one check box");

    }


  }

}

我想在这个 ajax 调用中发送那个布尔值并显示一个弹出窗口或警报框。如何实现这一目标?


慕田峪4524236
浏览 169回答 3
3回答

眼眸繁星

dataType: "JSON"从您的 ajax 调用中删除该属性。B'coz 你返回的是一个简单的布尔值。但是该属性表明它期望的响应是一个 JSON,在这种情况下这不是真的。然后使用像这样的代码success: function (data) {&nbsp; &nbsp; &nbsp; if (data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // your true code here&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// your false code here&nbsp; &nbsp; &nbsp; }&nbsp;}

炎炎设计

只需在成功函数中尝试这样的代码:&nbsp;success: function (data) {&nbsp; &nbsp; &nbsp; &nbsp; if (data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("Success!");&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("False value.");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }

largeQ

您似乎没有对您的服务器价值做任何事情。您需要将其返回给客户。由于您使用的是 spring,您应该能够将 json 返回到您的 ajax 调用。@RequestMapping(value="/testing", method = RequestMethod.POST, produces = "application/json")@ResponseBodypublic Map testAjax() {&nbsp; return Collections.singletonMap("flag", true);}然后您的 ajax 调用可以检索该值:&nbsp; &nbsp; &nbsp; &nbsp; success: function (data) {&nbsp; &nbsp; &nbsp; &nbsp; console.log("Success");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;alert(data.flag)&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; error: function (args) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("error");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(args);&nbsp; &nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答