asp.net中如何在后台执行js语句js中的document是什么.getElementById(str1).innerHTML=str2;

Internet Explorer (IE) JavaScript document.getElementById whackedness demo
If you're using IE and you see this bar... you'll need to click the bar and pick "Allow Blocked Content"
if you want to play with the JavaScript on this page.
No ActiveX is used.
Internet Explorer (IE) JavaScript document.getElementById whackedness demo
document.getElementById( String id ) explained
Usage: document.getElementById("IdOfYourElementOrJSObject")
&a href="mylink.htm" name="myLink" id="myLinkId"&myLink Text&/a&
The JavaScript
var link = document.getElementById("myLinkId");
When working correctly, document.getElementById() should return the element object whose id attrbute
matches the one specified in the call.
The Internet Explorer Problem
IE works correctly on elements that CAN'T have a name attribute.
It works incorrectly, however, on
elements that can.
As I researched this, I found a function in JavaScript I've never used before:
HTMLCollection.namedItem( String name )
This function seeks for any element within the collection whose id attribute value matches the name
specified in the call.
If it doesn't find one, it searches for any element whose name attribute
matches the name specified in the call.
The function returns the first element object it finds that meets
the criteria, or null if it can't find one.
My first thought was, Microsoft has their document.getElementById calling their namedItem() function.
But then I stepped back and realized through my experiment that IE seems to be matching against both
name and id at the same time to match the value.
As you'll notice below, I have two elements for each part of the experiment.
The first has the name
attribute filled with the id value "my[Element]" I'm wanting to look for.
I fill the second element's
id attribute with the same value.
IE, parsing from the top of the document down, finds the element
with the name="my[Element]" first and automatically takes it... it doesn't even wait to see if it
can find one with an id that matches first.
I can only assume this was done for optimizing this "convenience feature", but makes for some
serious puzzlement and aggravation in troubleshooting why the element a developer can't get to
who happens to name/id things in a way similar to what happens in my experiment.
Whatever reason,
they did it, it's wrong.
Please be careful in how you name/id things
On that same token, please don't name your submit buttons name="submit"... you'll override the
default submit property which is the form's submit() function... you'll start hating JavaScript
and wrongfully pointing fingers at browsers when you try to call myForm.submit() and it doesn't
... Moving on ...
Special Consideration ASP.net Developers Need To Be Aware Of
If you're an ASP.net programmer, and you need to create some dynamic JavaScript to work with
elements generated by ASP.net, not knowing the ID beforehand, it's crucial you use the
[myobject].ClientID property as opposed to the [myobject].UniqueID property
when creating your dynamic JavaScript.
This is ESPECIALLY true if you're using Internet Explorer
as your primary browser you develop against, doing secondary testing on other browsers.
If you use [myobject].UniqueId, you will be given the name="" value generated by ASP.net for
the HTML element.
This works fine in IE, because of the issue explained above... IE will find
the element with the name and return it to you.
The other browsers won't - so don't count on it.
Instead, use the [myobject].ClientID.
It will give you the value ASP.net injects into the
id="" attribute of the HTML element it generates, and will work in all browsers without any
special tweaking.
ASP.net / JavaScript example
function MyOnClickHandler( iURL )
top.document.location.href = iURL;
function HookupEvents()
var hyperlink = document.getElementById('&%# myLink.ClientID %&');
hyperlink.onclick = function(){ MyOnClickHandler(this.href) };
The Experiment
Try this in IE and other browsers like Firefox, Opera and Safari and see the differences.
name="myTextArea" id="textarea1"
name="textarea2" id="myTextArea"
name="myCheckbox" id="checkbox1"
name="checkbox2" id="myCheckbox"
name="myRadio" id="radio1"
name="radio2" id="myRadio"
Internet Explorer/Windows
Firefox/Windows
Clicking this button will show the "alt" for the fetched image.
Source Code
My Function For Utilizing document.getElementById() for Getting the Element Info
The Body's SourceJavaScript调用ASP.NET服务器端方法的最简单的方法
对于这样的问题,有很多解决方法,如果你返回的内容是简单的内容,如注册用户时候的验证信息,只需返回存在与否,那么可以采用下面最最简单的代码实现:
C# 代码&%@ Page Language="C#" %&
&!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"""&
&script runat="server"&& //测试方法1& public String GetSimpleMethod(String inputData)& {&&& //业务处理。&&& return "你输入的值:" + inputD& }
& protected void Page_Load(object sender, EventArgs e)& {&&& if (Request.QueryString["input"] != null)&&& {&&&&& Response.ClearContent();&&&&& Response.Write(GetSimpleMethod(Request.QueryString["input"]));&&&&& Response.End();&&& }& }&/script&
&html xmlns=""&&head id="Head1" runat="server"&& &title&&/title&& &script type="text/javascript"&&&& var textBox1 = "&%=TextBox1.ClientID %&";&&& function GetData() {&&&&& var t = document.getElementById(textBox1);&&&&& var h = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP");&&&&& h.open("GET", "&%=Request.FilePath %&?input=" + encodeURIComponent(t.value) + "&" + Date.parse(new Date()), true);&&&&& h.setRequestHeader("Connection", "close");&&&&& h.onreadystatechange = function() {&&&&&&& if (h.readyState == 4) {&&&&&&&&& if (h.status == 200) {&&&&&&&&&&& document.getElementById("info").innerHTML = h.responseT&&&&&&&&& }&&&&&&& }&&&&& }&&&&& h.send(null);&&& }&&& & &/script&&/head&&body&& &form id="form1" runat="server"&& &:TextBox ID="TextBox1" runat="server"&&/asp:TextBox&& &asp:Button ID="Button1" runat="server" Text="调用服务器方法 GetSimpleMethod" OnClientClick="GetData();" /&& &div id="info"&&/div&& &/form&&/body&&/&
对于需要返回复杂的对象,则需要对对象进行序列化等的处理,可以采取下面的简单方法。使用这个方法需要注意以下3点:1,后台方法必须标记为 [System.Web.Services.WebMethod] 属性;2,后台方法必须是 static 类型的静态方法;3,ScriptManager 必须设置 EnablePageMethods="true"。
ASPX 代码&%@ Page Language="C#" %&
&!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"""&
&script runat="server"&& //测试方法1& [System.Web.Services.WebMethod]& public static String GetSimpleMethod(String inputData)& {&&& return "你输入的值:" + inputD& }
& //测试方法2& [System.Web.Services.WebMethod]& public static System.Collections.Generic.List&BlogUser& GetListObjectMethod(int inputData)& {&&& System.Collections.Generic.List&BlogUser& ulist = new System.Collections.Generic.List&BlogUser&();&&& System.Random r = new Random();&&& for (int i = 0; i & 6; i++)&&& {&&&&& BlogUser u = new BlogUser();&&&&& u.UserName = "孟宪会" + inputData.ToString();&&&&& u.Score = r.Next(0, 100);&&&&& ulist.Add(u);&&& }&&&& }
& //用于返回的测试类。& public class BlogUser& {&&& public String UserName { }&&& public Int32 Score { }& } &/script&
&html xmlns=""&&head id="Head1" runat="server"&& &title&&/title&& &script type="text/javascript"&&&& var textBox1 = "&%=TextBox1.ClientID %&";&&& function GetData1() {&&&&& PageMethods.GetSimpleMethod(document.getElementById(textBox1).value, OnSucceeded1, OnFailed);&&& }
&&& function GetData2() {&&&&& PageMethods.GetListObjectMethod(document.getElementById(textBox1).value, OnSucceeded2, OnFailed);&&& }
&&& function OnSucceeded1(result, userContext, methodName) {&&&&& alert(result)&&& }&&& function OnSucceeded2(result, userContext, methodName) {&&&&& alert(result)&&&&& var html = "&table border=1&";&&&&& for (var i = 0; i & result. i++) {&&&&&&& html += "&tr&";&&&&&&& html += "&td&" + result[i].UserName + "&/td&&td&" + result[i].Score + "&/td&";&&&&&&& html += "&/tr&";&&&&& }&&&&& html += "&/table&";&&&&& document.getElementById("info").innerHTML =
&&& function OnFailed(error, userContext, methodName) {&&&&& if (error !== null) {&&&&&&& alert("调用方法错误:
" + error.get_message());&&&&& }&&& }& &/script&
&/head&&body&& &form id="form1" runat="server"&& &asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" /&& &asp:TextBox ID="TextBox1" runat="server"&&/asp:TextBox&& &asp:Button ID="Button1" runat="server" Text="调用服务器方法 GetSimpleMethod" OnClientClick="GetData1();" /&& &asp:Button ID="Button2" runat="server" Text="调用服务器方法 GetListObjectMethod" OnClientClick="GetData2();" /&& &div id="info"&&/div&& &/form&&/body&&/html&
(window.slotbydup=window.slotbydup || []).push({
id: '2467140',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467141',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467143',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467148',
container: s,
size: '1000,90',
display: 'inlay-fix'NetWork(10)
在ASP.NET中用JS如何调用Server端方法?
(1)这个需要用到AJAX了 ASP.NET AJAX(Atlas)版本的实现代码 首先是页面的HTML部分,注意ASP.NET AJAX(Atlas)独有的ScriptManager控件: &asp:ScriptManager ID=&ScriptManager1& runat=&server& /& &div& &input type=&button& value=&Get Server Time& id=&btnGetServerTime& onclick=&return btnGetServerTime_onclick()& /& &span id=&result& /& &/div& 然后是客户端JavaScript部分,注意用PageMethods.GetServerTime()这样的形式调用服务器端方法: function btnGetServerTime_onclick() { PageMethods.GetServerTime(cb_getServerTime); } function cb_getServerTime(result) { document.getElementById(&result&).innerHTML = } 服务器端代码如下,注意方法必须为静态,且添加[System.Web.Services.WebMethod]和[Microsoft.Web.Script.Services.ScriptMethod]两个属性: [System.Web.Services.WebMethod] [Microsoft.Web.Script.Services.ScriptMethod] public static string GetServerTime() { return DateTime.Now.ToString(); }&
(2)js.js文件: function p() { alert(&adfas&) } p(); aspx按钮事件: Response.Write(&&script lanuuage=javascript src='js.js'&&/script&&);
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:100513次
积分:1248
积分:1248
排名:千里之外
原创:10篇
转载:50篇
评论:14条
(5)(5)(1)(1)(1)(12)(2)(4)(5)(7)(5)(2)(2)(7)(1)您所在的位置: &
一款经典的ajax登录页面 后台asp.net
一款经典的ajax登录页面 后台asp.net
本文用AJAX编程实现一个经典的登录页面,有保存密码功能,页面上所有的控件都是html控件,没有服务器控件,具体实现过程见下文。
1. 新建一名为login.htm的静态网页文件,作为登录页面,如图
body标签代码,代码如下:&onkeydown&="enterLogin()"&& &&&style="text-align:&center"& &&border="1"&cellpadding="1"& && &&align="center"&style="width:&100&height:&20&background-color:&#99cccc"& &valign="middle"& &用户名:& &&align="center"&style="width:&74&height:&20&background-color:&#99cccc"&valign="middle"& &&id="txtusername"&style="width:&111&height:&19px"&type="text"&onblur&="checkuser()"&& &&align="center"&style="width:&199&height:&20&background-color:&#99cccc"& &valign="middle"&src=""&id&="imgCheck"&style&=&"visibility&:&"/&&id&="unMessage"& && && && &&align="center"&style="width:&100&height:&29&background-color:&#99cccc"& &valign="middle"& &密码:& &&align="center"&style="width:&74&height:&29&background-color:&#99cccc"&valign="middle"& &&id="txtpwd"&style="width:&107&height:&17px"&type="password"&& &&align="center"&style="width:&199&height:&29&background-color:&#99cccc"& &valign="middle"&id&="pwdMessage"& && && && &&align="center"&colspan="3"&style="background-color:&#99cccc"&valign="middle"& &&id="cbRememberPwd"&type="checkbox"&记住密码一个月& && && &&align="center"&colspan="3"&style="background-color:&#99cccc"&valign="middle"& &&id="btnOK"&type="button"&value="登录"&onclick&="login()"&& &&id="btnReset"&type="button"&value="重置"&onclick&="reset()"&& && && && &&&
2. 在login.htm中引入外部js代码&type&="text/javascript"&src&="aj.js"&&&type&="text/javascript"&src&="loginCookies.js"&&
其中aj.js为ajax封装的类,loginCookie.js为对Cookie操作的代码
aj.js代码如下://JScript文件 &&//ajax请求功能函数 &//get调用方式:(1)实例化&var&aj=new&ajax();&(2)调用get函数&aj.get(url,callback)&(3)写回调函数&function&callback(xhr){xhr.responsetext} &//post调用方式:(1)实例化&var&aj=new&ajax();&(2)调用post函数&aj.post(url,content,callback)&(3)写回调函数&function&callback(xhr){xhr.responsetext} &&//构造ajax对象 &&function&ajax()& &{ &function&getXHR()//获取xmlhttprequest &{ &var&request=false; &try& &{ &request&=&new&XMLHttpRequest(); &}& &catch&(trymicrosoft)& &{ &try& &{ &request&=&new&ActiveXObject("Msxml2.XMLHTTP"); &}& &catch&(othermicrosoft)& &{ &try& &{ &request&=&new&ActiveXObject("Microsoft.XMLHTTP"); &}& &catch&(failed)& &{ &request&=&false; &} &} &} &return& &} &&this.get&=&function&(openUrl,successFun)//ajax对象的get方法,通过get方式发送请求,openUrl为请求的页面,successFun为成功回调执行的函数 &{ &var&request&=&getXHR(); &request.open("get",openUrl,true); &//&request.onreadystatechange&=&function&() &//&{ &//&if&(request.readystate==4) &//&{ &//&if&(request.status==200) &//&{ &//&successFun(request); &//&} &//&} &//&}; &request.onreadystatechange&=&update; &function&update() &{ &if&(request.readystate==4) &{ &if&(request.status==200) &{ &successFun(request); &} &} &} &request.send(null); &} &&this.post&=&function&(openUrl,sendContent,successFun)//ajax对象的post方法,通过post方式发送请求,openUrl为请求的页面,successFun为成功回调执行的函数 &{ &var&request&=&getXHR(); &request.open("post",openUrl,true); &request.setRequestHeader("Content-Type",&"application/x-www-form-urlencoded");//告诉服务器发送的是文本 &request.onreadystatechange&=&update; &function&update() &{ &if&(request.readystate==4) &{ &if&(request.status==200) &{ &successFun(request); &} &} &} &request.send(sendContent); &} &} &
loginCookie.js代码如下//JScript文件 &&//SetCookie&保存一个Cookie。参数中除了name和value以外,其他可以省略。 &//GetCookie&通过一个Cookie的名字取出它的值。 &//DelCookie&删除一个Cookie,也就是让一个Cookie立刻过期。参数中除了name,其他可以省略。 &&&//测试 &//SetCookie("username",&"123");expires代表"月" &//alert(GetCookie("username")); &//DelCookie("username"); &//alert(GetCookie("username")); &&&&function&SetCookie(name,&value,&expires,&path,&domain,&secure)&{ &var&today&=&new&Date(); &today.setTime(today.getTime()); &if(expires)&{&expires&*=&2592000;&} &var&expires_date&=&new&Date(today.getTime()&+&(expires)); &document.cookie&=&name&+&"="&+&escape(value) &+&(expires&?&";expires="&+&expires_date.toGMTString()&:&"") &+&(path&?&";path="&+&path&:&"") &+&(domain&?&";domain="&+&domain&:&"") &+&(secure&?&";secure"&:&""); &} &&function&GetCookie(name)&{ &var&cookies&=&document.cookie.split(&';'&); &var&cookie&=&''; &&for(var&i=0;&i;&i++)&{ &cookie&=&cookies[i].split('='); &if(cookie[0].replace(/^\s+|\s+$/g,&'')&==&name)&{ &return&(cookie.length&=&1)&?&""&:&unescape(cookie[1].replace(/^\s+|\s+$/g,&'')); &} &} &return& &} &&function&Delcookie(name,&path,&domain)&{ &document.cookie&=&name&+&"=" &+&(path&?&";path="&+&path&:&"") &+&(domain&?&";domain="&+&domain&:&"") &+&";expires=Thu,&01-Jan-:01&GMT"; &}&
3. 写login.htm页面中的js代码,放在head标签之间&type&="text/javascript"&&window.onload&=&function&(){ &document.getElementById&('txtusername').focus();//用户名框获得焦点 &&if&(GetCookie('user_name')&!=&null&&&&GetCookie('user_pwd')&!=&null)//设置记住密码的登录页面 &{ &document.getElementById&("txtusername").value&=&GetCookie('user_name'); &document.getElementById&("txtpwd").value&=&GetCookie('user_pwd'); &} &} &&String.prototype.Trim&=&function()&//自定义的去除字符串两边空格的方法 &{& &return&this.replace(/(^\s*)|(\s*$)/g,&"");& &}& &&function&checkuser()//检验用户名是否正确 &{ &var&img&=&document.getElementById&("imgCheck") &img.src="iamges/blue-loading.gif";//设置图片及其可见性 &img.style.visibility&=&"visible"; &&var&aj&=&new&ajax();//以下为ajax请求 &var&username&=&document.getElementById&("txtusername").value.Trim(); &var&url&=&"login.aspx?uname="+escape(username); &aj.get(url,callback); &function&callback(obj) &{ &var&response&=&obj. &var&res&=&response.split('\n'); &if&(res[0]&==&"ok") &{ &img.src="iamges/icon-info.gif"; &document.getElementById&("unMessage").innerHTML&=&"用户名正确"; &} &else &{ &img.src="iamges/icon-warning.gif"; &document.getElementById&("unMessage").innerHTML&=&"用户名错误"; &} &} &} &&&function&login()//登录 &{ &if&(document.getElementById&("unMessage").innerText&==&"用户名错误") &{ &alert("你的用户名错误"); &} &else&if&(document.getElementById&("txtpwd").value&==&"") &{ &alert("请输入密码"); &} &else &{ &var&aj&=&new&ajax(); &var&username&=&document.getElementById&("txtusername").value.Trim(); &var&userpwd&=&document.getElementById&("txtpwd"). &var&url&=&"login.aspx?name="+escape(username)+"&pwd="+escape(userpwd); &aj.get(url,callback); &function&callback(obj) &{ &var&response&=&obj. &var&res&=&response.split('\n'); &if&(res[0]&==&"ok") &{ &if&(document.getElementById&("cbRememberPwd").checked) &{ &SetCookie('user_name',username,1);//保存密码一个月 &SetCookie('user_pwd',userpwd,1); &} &else &{ &SetCookie('user_name',username); &SetCookie('user_pwd',userpwd); &} &window.open&("loginIndex.htm","_self"); &} &else &&p;&{ &alert("密码错误"); &} &} &} &} &&function&reset()//重置 &{ &window.onload();//执行窗体登录事件 &document.getElementById&("txtusername").value=""; &document.getElementById&("txtpwd").value=""; &} &&function&enterLogin() &{ &if&(event.keyCode==13)&//如果按下的是Enter键的话,就执行登录语句 &{ &login(); &} &} &&
4. 新建一名为login.aspx的页面,该页面作为ajax请求的页面,login.aspx.cs代码如下protected&void&Page_Load(object&sender,&EventArgs&e) &{ &OleDbConnection&Conn&=&DBcon.get_con(); &&if&(Request["uname"]&!=&null) &{ &string&username&=&Request["uname"].ToString(); &string&strSql&=&"select&*&from&[user]&where&u_name='"&+&username&+&"'"; &Conn.Open(); &OleDbCommand&Comd&=&new&OleDbCommand(strSql,&Conn); &OleDbDataReader&dr&=&Comd.ExecuteReader(); &if&(dr.Read()) &{ &Response.Write("ok\n"); &} &else &{ &Response.Write("fail\n"); &} &//if&(Comd.ExecuteNonQuery()&&0) &//{ &//&Response.Write("存在这个用户\n"); &//} &//else &//{ &//&Response.Write("没有此用户名\n"); &//} &Conn.Close(); &} &&if&(Request["name"]&!=&null&&&&Request["pwd"]&!=&null) &{ &string&name&=&Request["name"].ToString(); &string&pwd&=&Request["pwd"].ToString(); &string&strSql&=&"select&*&from&[user]&where&u_name='"&+&name&+&"'"&+&"&and&u_pwd='"&+&pwd&+&"'"; &Conn.Open(); &OleDbCommand&Comd&=&new&OleDbCommand(strSql,&Conn); &OleDbDataReader&dr&=&Comd.ExecuteReader(); &if&(dr.Read()) &{ &Response.Write("ok\n"); &} &else &{ &Response.Write("fail\n"); &} &} &} &
5. 新建一名为loginIndex.htm的静态页面,作为用户登录之后的首页
其body标签代码如下:&&id&="username"&&&
6. 在loginIndex.htm页面引入loginCookie.js文件&type&="text/javascript"&src&="loginCookies.js"&&
7. 写loginIdex.htm页面的js代码,放在head标签之间&type&="text/javascript"&&window.onload&=&function&() &{ &if(GetCookie('user_name')==null&||&GetCookie('user_pwd')==null)//如果没有登录,而是直接在网页中输入网址的 &{ &alert('你还没有登录!\n返回到登陆页面。'); &window.navigate("login.htm"); &} &else &{ &var&uname&=&GetCookie('user_name'); &document.getElementById&('username').innerHTML&="欢迎你:&"&+&uname&+&"&&href='#'&onclick&=&'off()'注销";//提供"注销"按钮 &} &} &&function&off()//注销事件 &{ &if&(window.confirm("你真要注销吗?")) &{ &Delcookie("user_name"); &Delcookie("user_pwd"); &window.navigate("login.htm"); &} &} &&
8. 完成并演示
客户端代码较多,但是交互性很好,演示如下:
当输入完用户名,鼠标光标离开用户名框之后,系统会快速检验用户名是否合法
进入首页后,出现的窗口,带有当前登录的用户和注销按钮
当用户点击注销按钮时,会友情提示你是否真的注销
当你不是输入用户和密码登陆,也是直接在浏览器地址栏中输入首页网址的时候,系统会提示你没有登录,并直接返回到登陆页面。
当用户输入了有效的用户名和密码,并要求系统记住密码,用户下次进入到登录页面时,系统会把上次记住的用户名和密码显示在输入框中。。
并且这个时候直接在浏览器的地址栏中输入首页地址,也是能正常访问的。
【编辑推荐】
【责任编辑: TEL:(010)】
关于&&&&的更多文章
掌握一门技术,首要的是掌握其基础。笔者从事.NET相关开发多年,
作为移动开发者,WOT2016移动互联网技术峰会,绝对有你不得不来的理由。
外行说“大数据”、内行用“大数据”。不知道大数据,
本周开发频道的重点内容除了7月份的编程语言排行榜外
现在的淘宝可以让网民感受疯抢的喜悦,而网站的技术人
本书全面系统地概括了计算机网络的基本理论,详细阐述了OSI模型与网络协议、网络规划与综合布线、对等网络与服务器/客户端网络、
51CTO旗下网站

我要回帖

更多关于 js中的document是什么 的文章

 

随机推荐