作家
登录

让回调函数 showResponse 也带上参数的代码

作者: 来源:www.28hudong.com 2013-03-30 03:21:10 阅读 我要评论

function demo(){ var url="ajaxdemo.asp"; var paras = "" ; var myAjax = new Ajax.Request( url, { method: 'post', parameters: paras, onComplete: showResponse }); } function showResponse(originalRequest){ var html = originalRequest.responseText; alert(html); } 这是应用 prototype.js 后最常看见的ajax代码,由于 showResponse 不能直接带参数,在处理回调函数时有时候比较麻烦,比如要把返回的html值动态插入到某个元素里面去。今天终于想到了一种方法来解决这个问题: function demo(){ var url="ajaxdemo.asp"; var paras = "" ; var myAjax = new Ajax.Request( url, { method: 'post', parameters: paras, onComplete: function(originalRequest){showResponse(originalRequest,elemID)} }); } function showResponse(originalRequest,elemID){ var html = originalRequest.responseText; $(elemID).innerHTML = html; } 匿名函数这时充当了回调函数,而showResponse则变成一个普通方法了。变换了概念,问题就顺利解决。 解决了这个问题,还可以把这两个函数封装为一个函数: function demo(url,paras,updateElemID){ var myAjax = new Ajax.Request( url, { method: 'post', parameters: paras, onComplete: function(originalRequest){showResponse(originalRequest,updateElemID)} }); } function showResponse(originalRequest,elemID){ var html = originalRequest.responseText; $(elemID).innerHTML = html; } 只需要调用 demo(url,paras,updateElemID) 就能完成ajax的功能。爽。如果参数再扩展一下,增加一些动作函数,就不止是update某个元素的innerHTML这么简单了。

  推荐阅读

  document.open() 与 document.write()的区别

document.open() 打开一个新的空白文档,在IE下,open有两个默认参数,相当于document.open("text/html",'""),第二个参数只有一个值可选:replace,如果启用了该值,则新建的文档会覆盖当前页面的文档(相当于清>>>详细阅读


本文标题:让回调函数 showResponse 也带上参数的代码

地址:http://www.17bianji.com/kaifa2/JS/30207.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)