当前位置:首页 > H5 > 正文内容

Javascript封装的原生Ajax请求

高老师7年前 (2017-06-11)H52346

由于工作需要长期使用Ajax,一个页面重复的AJAX请求太多,于是封装起来,只需要编写回调函数

/*
-------------
使用方法:
1.ajaxrequest()函数执行准备的参数(1.请求地址2.发送数据字符串拼接3.type值可选get/post4.回调函数名称)
 
example:
 
ajaxrequest('login.php','user=1&pass=2','post',dealwith);
 
function dealwith()
{ 
if(myxmlhttprequest.readyState==4)
{
 
//mes的值是login.php页面返回的值
var mes= myxmlhttprequest.responseText;
 
//如果页面输出的是json值,还需要进行eval处理
var mes_obj=eval("("+mes+")");
 
 
} 
}
 
tip:ajaxrequest()以post方式发送数据user=1&pass=2,当服务器端收到请求并返回数据,此时
 
dealwith()方法来处理返回的数据
 
*/
 
 
//Allvariable 回调函数使用
var myxmlhttprequest="";
 
 
//Createxmlhttp 创建Ajax引擎
function getxmlhttpobject()
{ 
var xmlhttprequest;
 
if(window.ActiveXObject){
   xmlhttprequest=new ActiveXObject("Microsoft.XMLHTTP"); 
 
}
else{
xmlhttprequest=new  XMLHttpRequest();
}
    return xmlhttprequest;
}
 
 
//Createajaxrequest 发起请求
function ajaxrequest(url,data,type,callbackfunc)
{ 
myxmlhttprequest=getxmlhttpobject();
if (myxmlhttprequest)
{
myxmlhttprequest.open(type,url,true); 
myxmlhttprequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
myxmlhttprequest.onreadystatechange=callbackfunc;
myxmlhttprequest.send(data);
}
}


扫描二维码推送至手机访问。

版权声明:本文由高久峰个人博客发布,如需转载请注明出处。

本文链接:https://blog.5b1.cn/post/236.html

分享给朋友:
返回列表

没有更早的文章了...

下一篇:Javascript-WebSql的用法

“Javascript封装的原生Ajax请求” 的相关文章

Javascript-WebSql的用法

Javascript-WebSql的用法

    WebSql的原理是浏览器集成了sqllite数据库,Js操作,浏览器协助完成,没有多复杂。<!--          三个核心方法   ...

HTML5的离线缓存技术

HTML5的离线缓存技术

离线缓存的开启实例使用apache设置 1.apache配置文件搜索Addtype,我的addtype已经存在项目,如下    AddType application/x-compress .Z    AddType application/x-gz...

Javascript事件冒泡和捕捉

Javascript事件冒泡和捕捉

捕捉模式从DOM最顶层一直到最后一层,冒泡正好相反,具体运行以下实例测试.<!DOCTYPE html> <html> <head> <title>捕捉和冒泡</title> <meta charset="...

Javascript页面播放语音,Javascript语音读取页面的文字

Javascript页面播放语音,Javascript语音读取页面的文字

<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script type...

使用js让手机震动,js实现手机震动

使用js让手机震动,js实现手机震动

<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head>  ...

js cookie操作,js获取cookie值的方法,js 设置cookie

js cookie操作,js获取cookie值的方法,js 设置cookie

维护老项目中客户提到一个页面中有6个表单以上,导致每次保存一个其他的数据全部丢失,自己比较懒没有全部更换为ajax.用户每次输入完成或者选择完成记录cookie,每次提交后加载页面完成初始化cookie即可。以下代码取自w3school比较完善,之前在其他博客使用的经常出现bug,这个比较推荐使用:...