zoukankan      html  css  js  c++  java
  • 原生ajax函数封装

    原生ajax函数

    function ajax(json){
        json=json || {};
        if(!json.url){
        return;
       } json.data=json.data || {}; json.type=json.type || 'get'; var xmlhttp = null; if(window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); }else{ xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');  //兼容IE } //将data转换成字符串 var arr = []; for(var key in json.data){ arr.push(key + "=" + json.data[key]); } var postData = arr.join("&"); json.type = json.type.toUpperCase(); if(json.type === "GET"){ xmlhttp.open(json.type, json.url+'?'+postData+"&time=" +Math.random(), true); xmlhttp.send(); }else{ xmlhttp.open(json.type, json.url, true); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8'); xmlhttp.send(postData); } xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState === 4){ if(xmlhttp.status>=200 && xmlhttp.status<300 || xmlhttp.status==304){ json.success && json.success(xmlhttp.responseText); }else{ json.error && json.error(xmlhttp.status); } } }; }

    使用方法举例:

    ajax({
      url: '/login',
      data: {user: oUser.value, pass: oPass.value},
      success: function (str){
        var json=eval('('+str+')');
        if(json.ok){
          alert('登录成功');
        }else{
          alert('失败:'+json.msg);
        }
      },
      error: function (){
        alert('通信失败');
      }
    });
  • 相关阅读:
    Xcode下 gdb 调试命令
    Xcode 获取本地IP
    Linux终端提示符PS1设置(颜色)
    linux 客户端 Socket 非阻塞connect编程
    关于SIGPIPE导致的程序退出
    jQuery MiniUI开发系列之:数据验证
    支持Java Spring MVC
    支持ASP.NET MVC
    支持ASP.NET WebService
    jQuery MiniUI开发系列之:Ajax处理超时、服务端错误
  • 原文地址:https://www.cnblogs.com/lianchenxi/p/9665722.html
Copyright © 2011-2022 走看看