如何通过ajax从Java类获取JS函数的值

时间:2016-09-28 06:10:46

标签: javascript java ajax struts2

Jsp Page

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条件中。

1 个答案:

答案 0 :(得分:0)

在您的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;
                } 
            },