ajax的使用简单模板———登陆页面
发布时间:2020-12-16 01:49:11 所属栏目:百科 来源:网络整理
导读:$.ajax({ url: 'servlet/NodeInfoServlet' , type: 'post' , data:{ //交给服务端的设置信息 method: 'settingNodeInfo' , nodename: $( "#nodename_setting" ).val(), //取得设置框的值 nodeloc: $( "#nodeloc_setting" ).val(), nodeflag: $( "#nodeflag_s
$.ajax({
url:
'servlet/NodeInfoServlet'
,
type:
'post'
,
data:{
//交给服务端的设置信息
method:
'settingNodeInfo'
,
nodename: $(
"#nodename_setting"
).val(),
//取得设置框的值
nodeloc: $(
"#nodeloc_setting"
).val(),
nodeflag: $(
"#nodeflag_setting"
).val(),
nodeexpanse: $(
"#nodeexpanse_setting"
).val(),
nodeid:nodeidhandler
},
dataType:
'text'
,
//返回数据为text 服务端返回的数据类型
success:
function
(data){
// 调用 ajax后服务器给返回的 text对象,这里的text仅仅是个代号,不是text,是text对象而已
if
(data==
"true"
)
alert(
"成功"
);
else
if
(data==
"false"
)
alert(
"失败"
);
else
{
alert(
"error"
);
}
}
});
一般将被jquery封装过的ajax放在一个函数中,用函数包裹着,然后在合适的控件处调用。
url:提交到的那个处理页面,一般写上对应的servelt上面。
type:对应提交的方式,一般最好用post
data:{你自己填充的字段格式 parameter:value 多个用,隔开}
datatype: 服务器返回的数据类型,一般有text,json,
xml,
html,
script……
success:
function
(data){
ajax成功返回后的处理模块, 一般都是将服务器获得的参数设置到界面上。
data是回调参数,这个参数就是服务器返回的data数据
}
以后对于所有的表单提交,其实都可以封装在ajax中,不用非要在用表单提交submit。
example:
登陆表单:
<
div
class
=
"main-login"
>
<
div
class
=
"login-logo"
></
div
>
<
div
class
=
"login-content"
>
<
input
type
=
"hidden"
id
=
"path"
value
=
"
<%=
path
%>
"
/>
<
div
class
=
"login-info"
>
<
span
class
=
"user"
>
</
span
>
<
input
name
=
"username"
id
=
"username"
type
=
"text"
onblur
=
"checkUsername()"
value
=
""
class
=
"login-input"
/>
</
div
>
<
div
class
=
"login-info"
>
<
span
class
=
"pwd"
>
</
span
>
<
input
name
=
"password"
id
=
"password"
type
=
"password"
onblur
=
"checkPassword()"
value
=
""
class
=
"login-input"
/>
</
div
>
<
div
class
=
"login-oper"
>
<
input
type
=
"button"
id
=
"login"
onclick
=
"login()"
value
=
"登 录"
class
=
"login-btn"
/>
<
input
type
=
"button"
id
=
"reset"
onclick
=
"reset()"
value
=
"重 置"
class
=
"login-reset"
/>
</
div
>
</
div
>
</
div
>
这里的login()和reset()都是自定义函数,用于处理登陆事件和重置事件。
上面的ajax就可以封装登陆事件。
function login(){
$.ajax({
url:
'servlet/NodeInfoServlet'
,
type:
'post'
,
data:{
//交给服务端的设置信息
method:
'login'
,
nodename: $(
"#
username
"
).val(),
//用id取得设置框的值,id相当的好用,是个全局性的变量
nodeloc: $(
"#
password
"
).val(),
},
dataType:
'text'
,
//返回数据为text 服务端返回的数据类型
success:
function
(data){
// 调用 ajax后服务器给返回的 text对象,这里的text仅仅是个代号,不是text,是text对象而已
if
(data==
"true"
)
alert(
"成功"
);
else
if
(data==
"false"
)
alert(
"失败"
);
else
{
alert(
"error"
);
}
}
});
}
可以写一个对应的servlet用于处理这个登陆事件的服务器响应:
protected
void
doPost(HttpServletRequest
request
,HttpServletResponse
response
)
throws
ServletException,IOException {
response
.setContentType(
"text/html;charset=utf-8"
);
request
.setCharacterEncoding(
"utf-8"
);
response
.setCharacterEncoding(
"utf-8"
);
PrintWriter
out
=
response
.getWriter();
if
(查询成功
)
out
.print(
"false"
); //这个字符串会被写到success的data字段中
else
out
.print(
"true"
);
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |