上篇文章介绍了在js调用Webservice的方法,此方法在IE的浏览器上是可行的,而且效率也不错,但我在项目中碰到要适用多种浏览器的实现,这时,使用XMLDOM就无法调用了。比如在FireFox和Opera中使用,将会出现“参数错误”之类的信息了。
经过测试和了解,结果发现FireFox是不支持var xmlDoc =new ActiveXObject("Microsoft.XMLDOM")这种ActiveXObject对象的。所以采用了js + xmlHttp,这样也是ajax的一种实现,代码如下:
var strurl="../WebService/Users.asmx/Login?UserName=" + strUser + "&Password=" + strPass;
var xmlHttp;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');
}
xmlHttp.open("GET",strurl, false);
xmlHttp.send(null);
当然,调用会有Get和Post两种方法,此处只讲Get方法。后台的Webservice是这样写的:
[WebMethod(Description = "判断用户名和密码是否正确", EnableSession = true)]
public void Login(string UserName, string Password)
{
Context.Response.ContentType = "text/xml";
if (Bussiness.userlogin(UserName,Password))
{
Context.Response.Write("<loginvalue>1</loginvalue>");
}
else
{
Context.Response.Write("<loginvalue>0</loginvalue>");
}
}
由逻辑可知,登录成功则打印1,否则打印0,为了更好地取值,我在前面加了loginvalue以作区别,这样取值时,可以通过xml通到节点的值:
myresponse=xmlHttp.responseXML.getElementsByTagName("loginvalue")[0].firstChild.nodeValue;
if (myresponse=="1")
{
window.location.href="Index.aspx";
}
else if(myresponse=="0")
{
alert("用户名或密码错误,请重新登录!");
}
这样就成功地实现了由js调用webservice的登录功能,其中使用try catch的错误处理,以避免由于浏览器的不同而发生的错误。
经过测试和了解,结果发现FireFox是不支持var xmlDoc =new ActiveXObject("Microsoft.XMLDOM")这种ActiveXObject对象的。所以采用了js + xmlHttp,这样也是ajax的一种实现,代码如下:
var strurl="../WebService/Users.asmx/Login?UserName=" + strUser + "&Password=" + strPass;
var xmlHttp;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');
}
xmlHttp.open("GET",strurl, false);
xmlHttp.send(null);
当然,调用会有Get和Post两种方法,此处只讲Get方法。后台的Webservice是这样写的:
[WebMethod(Description = "判断用户名和密码是否正确", EnableSession = true)]
public void Login(string UserName, string Password)
{
Context.Response.ContentType = "text/xml";
if (Bussiness.userlogin(UserName,Password))
{
Context.Response.Write("<loginvalue>1</loginvalue>");
}
else
{
Context.Response.Write("<loginvalue>0</loginvalue>");
}
}
由逻辑可知,登录成功则打印1,否则打印0,为了更好地取值,我在前面加了loginvalue以作区别,这样取值时,可以通过xml通到节点的值:
myresponse=xmlHttp.responseXML.getElementsByTagName("loginvalue")[0].firstChild.nodeValue;
if (myresponse=="1")
{
window.location.href="Index.aspx";
}
else if(myresponse=="0")
{
alert("用户名或密码错误,请重新登录!");
}
这样就成功地实现了由js调用webservice的登录功能,其中使用try catch的错误处理,以避免由于浏览器的不同而发生的错误。
浙公网安备 33010602011771号