当我们改变某一个人或某几个人的某项分值实现无刷新写入数据库。
首先,我们需要声明xmlhttprequest对象
复制代码 代码如下:
//声明xmlhttprequest对象
var xmlhttp;
function createxmlhttp() {
if (window.xmlhttprequest) {
xmlhttp = new xmlhttprequest(); //mozilla浏览器
}
else if (window.activexobject) {
try {
xmlhttp = new activexobject(msxml2.xmlhttp); //ie老版本
}
catch (e)
{ }
try {
xmlhttp = new activexobject(microsoft.xmlhttp); //ie新版本
}
catch (e)
{ }
if (!xmlhttp) {
window.alert(不能创建xmlhttprequest对象实例!);
return false;
}
}
}
同时,需要回调函数来确定是否修改成功
复制代码 代码如下:
//更新或者添加记录的回调函数(检验是否评分成功)
function modifyscore ()
{
if (xmlhttp.readystate == 4)
{
// if (xmlhttp.status == 200)
{
if (xmlhttp.responsetext == true)
{
}
else
{
// alert(评分失败,请重新评分或者与管理员联系);
}
}
}
}
准备工作完成之后,下面就是关键的一步:
因为需要在修改分值的时候写入数据库,所以只需要在上篇博客中提高的改变下拉框值(循环选中项时)的执行这样一段代码:
复制代码 代码如下:
//获取互评id
var criticsid = checkbox[i].value;
//把修改值写入数据库
//获取项目分数
var scoreall = document.getelementbyid(score +checkbox[i].value + srcelem.id + );
var accessallscore = scoreall.outertext;
//获取项目编号
var assess = document.getelementbyid(assess + srcelem.id);
var assessid = assess.title;
createxmlhttp(); //创建xmlhttprequest对象
//把数据传入到另一个页面执行
var url = criticsagainajax.aspx?criticsid= + criticsid +&assessid= + assessid + &accessallscore= +accessallscore + &event=allcriticsinfo;
xmlhttp.open(post, url, true);
// xmlhttp.setrequestheader(content-type,application/x-www-form-urlencoded);
xmlhttp.onreadystatechange = answeronekindquestion;
xmlhttp.send(null);
最后,我们只需要在criticsagainajax.aspx获取参数,并执行写入数据库就可以了
复制代码 代码如下:
//获取参数
if(request.querystring[event].tostring() ==allcriticsinfo)
{
string criticsid = request.querystring[criticsid].tostring();
string assessid = request.querystring[assessid].tostring();
string accessallscore =request.querystring[accessallscore].tostring();
}
参数传过来之后,写入数据库就很容易了,这里就不提了。
这样,在前台显示的效果就是没有刷新,时时的把数据写入到数据库。只是把脏活累活都交给criticsagainajax.aspx页面来干,这也是一种不错的分工。
这样写出了少刷新以外,还有另一个好处就是ajax是异步操作,即在js页面中把数据抛到criticsagainajax.aspx之后,他就继续执行,他不考虑criticsagainajax.aspx是否执行完成,可能抛过来100条数据,写入数据库需要三秒钟,而抛过来的时间是非常快的,可能就零点几秒,所以用户的感觉会非常好,他不需要在选中后等半天才能继续执行。
