Ajax使用小结

来源:互联网 发布:网上怎么自学淘宝 编辑:程序博客网 时间:2024/06/03 08:44

    项目真正使用,不可能每一条处理就刷新页面与服务器交互提交一次;也不能在后台每处理一次就刷新页面与服务器交互,所以在这里使用Ajax非常必要,以下就以简单的例子说明Ajax在此的使用过程。

添加属性

textBox.Attributes.Add("Onblur", "javascript:return CheckFraction(event.srcElement)&&JudgeQuestions('" + tableName.Trim() + "','" + id + "','" + textBox.ID + "')");

JS代码

//声明XMLHttpRequest对象var xmlHttp;function createXMLHTTP() {    if (window.XMLHttpRequest) {        xmlHttp = new XMLHttpRequest(); //其它浏览器    }    else if (window.ActiveXObject) {        try {            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); //IE老版本        }        catch (e)        { }        try {            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE新版本         }        catch (e) {            alert('创建XMLHTTP对象失败!');        }        if (!xmlHttp) {            window.alert("不能创建XMLHttpRequest对象实例!");            return false;        }    }}function JudgeQuestions(tableName, questionId, TextBoxId) {        //读取分数ctl00$ContentPlaceHolder1$t_    TextBoxId = "ContentPlaceHolder1_" + TextBoxId;    var fraction = document.getElementById(TextBoxId).value;    var pattern = /^[0-9]+(.[0-9]{1})?|([0-9]|[1-9][0-9]|100)$/;    var flag = pattern.test(fraction);    if (flag == false) {        alert("分数应该是数字类型");        return false;    }    createXMLHTTP(); //创建XMLHttpRequest对象    var url = "MarkToServer.aspx?tableName=" + tableName + "&id=" + questionId + "&fraction=" + fraction + "&Event=" + "Judge";    xmlHttp.open("Post", url, true);    xmlHttp.onreadystatechange = JudgeResult;    xmlHttp.send(null);}//判断判卷是否成功function JudgeResult() {    if (xmlHttp.readyState == 4) {        if (xmlHttp.status == 200) {            if (xmlHttp.responseText == "true") {            }            else {                alert("评分失败,请重新评分或者联系管理员");            }        }    }}

MarkToServer.aspx

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Collections;using System.Configuration;using System.Data;using System.Web.Security;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using ExamSys.Pages.Common;using Entity;using BLL.BLLPaperManage;public partial class Pages_UIPaperManage_MarkToServer : System.Web.UI.Page{    OnlineMarkBLL markBLL = new OnlineMarkBLL();    protected void Page_Load(object sender, EventArgs e)    {        //分别得到数据表名称、试题id、试题所得分数        string tableName = Request.QueryString["tableName"].ToString();        int id = Convert.ToInt32(Request.QueryString["id"].ToString());        int fraction = Convert.ToInt32(Request.QueryString["fraction"].ToString());        if (Request.QueryString["Event"].ToString() == "Judge")        {            if (markBLL.UpdateOneQuestionRecordFraction(tableName, id, fraction))            {                Response.Write("true");                Response.End();            }            else            {                Response.Write("false");                Response.End();            }        }    }}

BLL层

/// <summary>/// 更新一条答题记录/// </summary>/// <returns></returns>public bool UpdateOneQuestionRecordFraction(string tableName, int id, int fraction){    onlineMarkDAL.ModifyFraction(tableName, id, fraction);    return true;}

DAL层

    /// 更改评分    /// </summary>    /// <param name="id"></param>    /// <param name="fraction"></param>    /// <returns></returns>    public bool ModifyFraction(string tableName, long id, int fraction)    {        try        {            string cmdText = "";            //定义存储过程字符串,并且赋值            cmdText = "update " + tableName + " set fraction=@fraction where id=@id";            //给参数赋值            SqlParameter[] paras = new SqlParameter[]{            new SqlParameter ("@id",id ),            new SqlParameter ("@fraction",fraction )};            //执行命令            if (SQLHelper.ExecuteNonQuery(cmdText, paras, CommandType.Text) >= 0)            {                return true;            }            return false;        }        catch (Exception e)        {            throw e;        }        finally {            SQLHelper.Close();        }    }}

    原理比较简单,就是给TextBox控件添加属性,当焦点离开时触发JS的JudgeQuestions函数,JS再与MarkToServer.aspx交互(使用ashx更好),再就是常见的三层结构:UI层调用BLL层的UpdateOneQuestionRecordFraction,BLL层再调用DAL层的ModifyFraction函数即可(实体层和SQLHelper省略)。

    难的不是怎么使用,而是在什么时候想到使用。