在jsp中用ajax调用另一个acttion并取得返回值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38262968/article/details/82428456

在后端写一个action来检验验证码是否正确,然后在jsp中ajax调用,并根据返回值执行不同的操作:

后端代码:

将判断结果写入服务器的response对象中,然后前端代码通过ajax调用的时候会直接获取到返回结果</font>

public void check(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String result = "error";

String clientCheckcode = request.getParameter("validateCode");//接收客户端浏览器提交上来的验证码

String serverCheckcode = (String) request.getSession().getAttribute("checkcode");//从服务器端的session中取出验证码

if (clientCheckcode.equals(serverCheckcode.toLowerCase())) {//将客户端验证码和服务器端验证比较,如果相等,则表示验证通过

System.out.println("验证码验证通过!");

result = "ok";

response.getWriter().print(result);   //在这里往response对象中写入判断结果

}

else

{

System.out.println("验证码验证失败!");

response.getWriter().print(result);

}

}

把方法返回值设为空,然后把方法执行的返回值放入响应流中。

前端调用: 后台返回结果会进success : function(data)里面。

function checkImg(code){

$.ajax({

type: "post",

url: "${pageContext.request.contextPath}/Check/check.action",

data:{

validateCode:code

},

dataType: "text",

success:function(data){    //data即执行该action后返回的结果

if(data == "error"){

$('#validateCode').value=''; //这个为前端页面的验证码输入框

alert("验证码错误!");

changeImg("nl"); //如果验证码错误就更换验证码图片

}

},

error:function(data){

if(data == "error"){

$('#validateCode').value='';

changeImg("nl");

}

}

});

ajax调用成功时返回数据以放入function的data中

猜你喜欢

转载自blog.csdn.net/qq_38262968/article/details/82428456
今日推荐