AJAX简介:
Ajax的全称是:AsynchronousJavaScript+XML。Ajax不是一个技术,它实际上是几种技术,每种技术都有其独特之处,合在一起就成了一个功能强大的新技术。
使用AJAX的异步模式,浏览器就不必等用户请求操作,也不必更新整个窗口就可以显示新获取的数据。只要来回传送采用XML格式的数据,在浏览器里面运行的JavaScript代码就可以与服务器进行联系。JavaScript代码还可以把样式表加到检索到的数据上,然后在现有网页的某个部分加以显示。
通过代码先理解一下AJAX是如何实现局部刷新滴!
/// <summary> /// 显示一道试题的题干和答案以及答题记录 /// </summary> public void ShowOneExamOneTypeOneQuestion(int pageIndex) { //得到试题id DataTable dt=(DataTable)Session["dtOneTypeQuestionId"]; int indexQus=(int)Session["questionIndex"]; int intquestionIndex = (int)dt.Rows[indexQus]["QuestionID"]; Session["questionIndexhjy"] = intquestionIndex; //获取考试id值 string ExamID = DropExam.SelectedItem.Value; //Session["ExamIDHJY"] = ExamID; //查找试题记录--答题记录表 string tableRecord = Convert.ToString(Session["tableRecord"]); //题型的value string UserName = Session["UserNo"].ToString(); //string UserName = "xvshu"; string questionType = dropQuestionType.SelectedItem.Value; //调用王永俊的方法,查看答题记录前20条,并写入教师姓名 string isCheck; if (chkIsChecked.Checked == true) { isCheck = "是"; } else { isCheck = "否"; } Session["isCheckhjy"] = isCheck; //给hashtable赋值 Hashtable map = new Hashtable(); map.Add("TableNameRecord",tableRecord);//题型value和表名 map.Add("QuestionType",questionType); map.Add("Teacher",UserName); map.Add("QuestionID",intquestionIndex); map.Add("ExamID",ExamID); map.Add("IsCheck",isCheck); QuestionContextBLL awardingBLL = new QuestionContextBLL(map); //查出答题记录 DataTable dtOneQuestionRecords = awardingBLL.SelectRecordTopbyQuestionID(map); if (dtOneQuestionRecords.Rows.Count == 0) { Session["questionType"] = null; //MessageBox.Show(this,"已判完此题!"); lblMessage.Text = "已判完此题!"; return; } Session["record"] = dtOneQuestionRecords; //循环写入教师姓名 for (int i = 0; i < dtOneQuestionRecords.Rows.Count; i++) { string id = dtOneQuestionRecords.Rows[i][0].ToString(); Hashtable hmap = new Hashtable(); hmap.Add("TableNameRecord",tableRecord);//题型value和表名 hmap.Add("QuestionType",questionType); hmap.Add("Teacher",UserName); hmap.Add("ExamID",ExamID); hmap.Add("ID",id); bool bolTeacher = awardingBLL.UpdateRecordTeacherByID(hmap); } //得到试题id集合--所有达此试题id的答题记录 DataTable dtOneTypeQuestionId = (DataTable)(Session["dtOneTypeQuestionId"]); //DataTable dtOneTypeQuestionId = dtOneQuestionRecords.Columns["QuestionID"]; //获取题库表名 string tableName = Convert.ToString(Session["tableName"]); if (dtOneTypeQuestionId == null || dtOneTypeQuestionId.Rows.Count <= 0) { return; } if (dropQuestionType.SelectedItem.Value.Trim() == "请选择") { return; } //查找试题 Hashtable mapQuestion = new Hashtable(); int questionID = Convert.ToInt32(dtOneTypeQuestionId.Rows[indexQus]["QuestionID"]); mapQuestion.Add("TableName",tableName); mapQuestion.Add("QuestionID",questionID); mapQuestion.Add("QuestionType",questionType); QuestionContextBLL contentBLL = new QuestionContextBLL(mapQuestion); DataTable dtOneQuestion = contentBLL.SelectQuestionContentbyRecordQuestionID(mapQuestion); fenzhi = dtOneQuestion.Rows[0]["Fraction"].ToString(); //显示题干 web_class_mark.CreatQuestion createQuestion = new web_class_mark.CreatQuestion(); web_class_mark.QuestionsPage questionPage = new web_class_mark.QuestionsPage(); DataSet dsAllQuestion = new DataSet(); dsAllQuestion.DataSetName = "T_hejingyuan"; dtOneQuestion.TableName = dropQuestionType.SelectedItem.Value.Trim(); dsAllQuestion.Tables.Add(dtOneQuestion.Copy()); questionPage = createQuestion.StuCreateQuestion(dsAllQuestion,questionBody,"0","00000","000"); questionPage.ShowPage(); //显示答案 Session["Fraction"] = dtOneQuestion.Rows[0]["Fraction"].ToString(); lblQuestionAnswer.Text = dtOneQuestion.Rows[0]["CorrectAnswer"].ToString(); ///何静媛2013年11月22日 Session["answerRecordCount"] = dtOneQuestionRecords.Rows.Count; //界面上显示出共有多少条答题记录 lblRecordCount.Text = dtOneQuestionRecords.Rows.Count.ToString(); //显示答题记录 ShowAnswerRecord(dtOneQuestionRecords,tableRecord,pageIndex); } /// <summary> /// 显示某道试题的答题记录,显示某一部分。 /// </summary> /// <param name="dtOneQuestionRecords">查询出的要显示的所有答题记录集合</param> /// <param name="pageIndex">要显示某个区间段的</param> private void ShowAnswerRecord(DataTable dtOneQuestionRecords,string tableRecord,int pageIndex) { myframe.Attributes["src"] = "StuRecords.aspx"; }
/// <summary> /// 窗体加载时,判断session的值是否为空,空则加载子窗体空白页,否则执行子窗体的事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender,EventArgs e) { if (Session["questionType"] != null && Session["ExamIDHJY"]!=null) { lblFraction.Text = ""; ShowStuRecord(); } else { tblAutoTable.Controls.Clear(); } } public void ShowStuRecord() { //得到试题id int questionIndex = Convert.ToInt32(Session["questionIndexhjy"]); //获取考试id值 string ExamID = Session["ExamIDHJY"].ToString(); //查找试题记录--答题记录表 string tableRecord = Convert.ToString(Session["tableRecord"]); //题型的value string UserName = Session["UserNo"].ToString(); //string UserName = "xvshu"; string questionType = Session["questionType"].ToString(); //调用王永俊的方法,查看答题记录前20条,并写入教师姓名 string isCheck = Session["isCheckhjy"].ToString(); Hashtable map = new Hashtable(); map.Add("TableNameRecord",questionIndex); map.Add("ExamID",isCheck); QuestionContextBLL awardingBLL = new QuestionContextBLL(map); //查出答题记录 DataTable dtOneQuestionRecords = awardingBLL.SelectRecordTopbyQuestionID(map); Session["recordCountHJY"]=dtOneQuestionRecords.Rows.Count; if (dtOneQuestionRecords.Rows.Count == 0) { if (isCheck == "是") { MessageBox.Show(this,"没有已判的答题记录!"); } else { MessageBox.Show(this,"此题已经判完,请点击下一试题!"); } } lblFraction.Text = "标准分数:" + Session["Fraction"]; int pageIndex = 0; for (int i = 5000 * pageIndex; i < 5000 * pageIndex + 5000 && i < dtOneQuestionRecords.Rows.Count; i++) { //显示答写的试题答案 TableCell tc = new TableCell(); tc.Text = (i + 1).ToString() + "答案:" + dtOneQuestionRecords.Rows[i]["ExamAnswer"].ToString(); TableRow tr = new TableRow(); //设置实例化的tr的宽度 tr.Width = System.Web.UI.WebControls.Unit.Pixel(720); tr.Cells.Add(tc); tblAutoTable.Rows.Add(tr); TextBox textBox = new TextBox(); //得到试题记录的id号 string id = dtOneQuestionRecords.Rows[i]["ID"].ToString(); textBox.Text = dtOneQuestionRecords.Rows[i]["Fraction"].ToString(); //给评分控件设置id号 textBox.ID = tableRecord.Trim() + dtOneQuestionRecords.Rows[i]["ID"].ToString(); //给textBox注册Onblur(失去焦点)事件 textBox.Attributes.Add("Onblur","javascript:return CheckFraction(event.srcElement)&&JudgeQuestions('" + tableRecord.Trim() + "','" + id + "','" + textBox.ID + "')"); TableCell tc1 = new TableCell(); tc1.Controls.Add(textBox); TableRow tr1 = new TableRow(); tr1.Cells.Add(tc1); tblAutoTable.Rows.Add(tr1); } }
JS代码:
//更新一道试题的得分 function JudgeQuestions(tableName,questionId,TextBoxId) { //读取所给分数ctl00$ContentPlaceHolder1$t_ //TextBoxId = "ContentPlaceHolder1_" + TextBoxId; TextBoxId = TextBoxId; var fraction = document.getElementById(TextBoxId).value; //修改分数的正则表达式允许有小数 var pattern = /^[0-9]+(.[0-9]{1})?|([0-9]|[1-9][0-9]|100)$/; // var pattern = /^([0-9]|[1-9][0-9]|100)$/; var flag = pattern.test(fraction); if (flag == false) { alert("分数应该是数字类型"); return false; } createXMLHTTP(); //创建XMLHttpRequest对象,XMLHttpRequest可以提供不重新加载页面的情况下更新网页 var url = "MarkToServer.aspx?tableName=" + tableName + "&id=" + questionId + "&fraction=" + fraction + "&Event=" + "Judge"; xmlHttp.open("Post",url,true); //发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态 //onreadyStateChange事件可指定一个事件处理函数来处理XMLHttpRequest对象的执行结果 xmlHttp.onreadystatechange = JudgeResult; //xmlhttp的send是传递参数用的,但是只有在使用post方式提交请求的时候才有用 xmlHttp.send(null); } //readyState有五种可取值0:尚未初始化,1:正在加载,2:加载完毕,3:正在处理;4:处理完毕。一旦readyState属性的值变成了4,就可以从服务器返回的响应数据进行访问了。 //Status存储了服务器端返回的Http请求响应代码,它表示请求的处理结果,常见响应代码的含义如右。在Ajax开发中,最常用就是200这个响应码,代码如下: //判断判卷是否成功 function JudgeResult() { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { //是后台返回到前台的消息 if (xmlHttp.responseText == "true") { } else { alert("评分失败,请重新评分或者联系管理员"); } } } }
MarkToServer.aspx页面:
protected void Page_Load(object sender,EventArgs e) { //分别得到数据表名称、试题id、试题所得分数 //调用王永俊的方法往回更新值 //获取传来的参数值 string questionType = Session["questionType"].ToString(); string tableName = Request.QueryString["tableName"].ToString(); int id = Convert.ToInt32(Request.QueryString["id"].ToString()); decimal fraction = Convert.ToDecimal(Request.QueryString["fraction"].ToString()); //获取时间戳 PublicBLL pubBLL = new PublicBLL(); string timestamp = pubBLL.GetTime(); if (Request.QueryString["Event"].ToString() == "Judge") { Hashtable map=new Hashtable(); //给hashtable赋值传参 map.Add("TableNameRecord",tableName); map.Add("Fraction",fraction); map.Add("ID",id); map.Add("QuestionType",questionType); map.Add("Timestamp",timestamp); QuestionContextBLL questionContext = new QuestionContextBLL(map); //调用B层方法,返回是否成功 if (questionContext.UpdateRecordFractionbyID(map)) { Response.Write("true"); Response.End(); } else { Response.Write("false"); Response.End(); } } }
总结:
Attributes.Add("javascript事件","javascript语句");
例如:Button1.Attributes.Add("onclick","returncheckSame()");//为Button1添加onclick()事件,Button为服务器控件
传统的 web 应用程序会把数据提交到 web 服务器(使用 HTML 表单)。在 web服务器把数据处理完毕之后,会向用户返回一张完整的新网页。
由于每当用户提交输入,服务器就会返回新网页,传统的 web 应用程序往往运行缓慢,且越来越不友好。
通过 AJAX,web 应用程序无需重载网页,就可以发送并取回数据。完成这项工作,需要通过向服务器发送 HTTP请求(在幕后),并通过当服务器返回数据时使用 JavaScript 仅仅修改网页的某部分。
原文链接:https://www.f2er.com/ajax/165516.html