【问题标题】:How can I get the value from Java class to JS function through ajax如何通过ajax从Java类获取值到JS函数
【发布时间】:2016-09-28 06:10:46
【问题描述】:

Jsp 页面

function emailValidate() {
    var email = document.getElementById("email").value;

    var url = "emailValidate.action?email=" + email;

    $.ajax({
                type : 'POST',
                url : url,
                dataType : 'json',
                async : false,

                success : function(data) {
                    console.log(data);                      
                    alert($('#ajaxResponse').text(jsonResponse.isUserAllow));

                     if (....) {
                        alret("This Email-Id is alreay registered.");
                    } else {
                        document.getElementById("submit").disabled = true;
                    } 
                },
                failure : function(data) {
                    alert('Server side failure with status code '
                            + response.status);
                }
            })

Java 类:

   public String execute() {

    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    email = request.getParameter("email");

    int isUserAllow = 0;

    try {
        EmailValidationDaoImp evl = new EmailValidationDaoImp();
        isUserAllow = evl.emailValidation(email);
        response.setContentType("text/html");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter() .write("isUserAllow:"+isUserAllow);
    }

    catch (Exception e) {
        logger.error("Exception in RegAction.java : " + e);
    }

    return "success";
}

我曾经使用过 Struts2。 我想将 isUserAllow 的值发回给 JS 函数,这样我就可以把它放在 if 条件中。

【问题讨论】:

  • 不要永远、永远、永远、永远、永远
  • ...永远,永远,永远使用async : false
  • Aaand,它是 alert 不是 alreterror 不是 failure 并且您似乎没有任何名为 jsonResponse 甚至 response 的名称,它们都被命名为 @ 987654330@
  • 对于特定字段也使用data.isUserAllow
  • 正如你所说,我已经通过 beflow 改进了。

标签: javascript java ajax struts2


【解决方案1】:

在你的 java 文件中:而不是这个,

    response.setContentType("text/html");
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter() .write("isUserAllow:"+isUserAllow);

你可以使用下面的代码

PrintWriter out = response.getWriter();
out.print(isUserAllow);

并删除return type("success")

在您的 js 文件中,您可以进行如下修改:

      success : function(data) {
                console.log(data);                    
                 if (data == 0) {
                    alert("This Email-Id is alreay registered.");
                } else {
                    document.getElementById("submit").disabled = true;
                } 
            },

【讨论】:

  • 别那样做。
  • @Poori 它不起作用。但是我是如何解决它的,它是如何与 struts2 一起工作的,现在它是如何工作的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-11
  • 1970-01-01
  • 2020-07-07
  • 2013-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多