ajax 封装成 我喜欢的样子

需要jquery支持

//创建ajax类
function ajaxobj(){
  this.url="";
  this.data="";
  this.type="post";
  this.async=true;//true:同步     false:异步
  this.success;//成功时执行
    this.error;//失败时执行
  this.complete=function(XHR,TextStatus){//完成时执行
   if(XHR.statusText!="OK"){
            if(typeof this.error == "function"){this.error();}
            console.warn(that.url+"->"+XHR.statusText)
    }
  };
  this.timeout=120000;//120秒超时
  this.send=function(){
    $.ajax(this);
  }
}
function ajax(url,_post,callback,error){
      var _ajax = new ajaxobj();
      _ajax.url=url;
      _ajax.data=_post;
      _ajax.success=callback;
      _ajax.error=error;
      _ajax.send();
    }

 
原生js ajax
来源http://www.cnblogs.com/a757956132/p/5603176.html

/* 封装_ajax函数
 * @param {string}opt.type http连接的方式,包括POST和GET两种方式
 * @param {string}opt.url 发送请求的url
 * @param {boolean}opt.async 是否为异步请求,true为异步的,false为同步的
 * @param {object}opt.data 发送的参数,格式为对象类型
 * @param {function}opt.success ajax发送并接收成功调用的回调函数
 */
   function _ajax(opt) {
        opt = opt || {};
        opt.method = opt.method.toUpperCase() || 'POST';
        opt.url = opt.url || '';
        opt.async = opt.async || true;
        opt.data = opt.data || null;
        opt.success = opt.success || function () {};
        opt.error = opt.error|| function () {};
        var xmlHttp = null;
        if (XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        }
        else {
            xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
        }var params = [];
        for (var key in opt.data){
            params.push(key + '=' + opt.data[key]);
        }
        var postData = params.join('&');
        if (opt.method.toUpperCase() === 'POST') {
            xmlHttp.open(opt.method, opt.url, opt.async);
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
            xmlHttp.send(postData);
        }
        else if (opt.method.toUpperCase() === 'GET') {
            xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
            xmlHttp.send(null);
        }
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
              opt.success(xmlHttp.responseText);
            }
            if(xmlHttp.readyState == 4 && xmlHttp.status != 200){
              opt.error(xmlHttp);
              console.warn(`[${opt.method}]${opt.url} -> ${xmlHttp.status}-${xmlHttp.statusText}`)
            }
        };
    }
        /**
        * 我喜欢的样子
        */
    function ajax(url,_post,callback,error){
      _ajax({
        method: 'POST',
        url: url,
        data: _post,
        success: function (response) {
           callback(response);
        },
        error: error
    });
    }

thinkphp3.2生成验证码

来源:http://www.thinkphp.cn/topic/23989.html

1在控制器里定义一个方法来生成验证码:
public function selfverify(){
$verify = new \Think\Verify($config);
$verify->entry();
}

2模板里面引用验证码:
<IMG onclick="this.src=this.src+'?'+Math.random()" src="{:U('login/selfverify')}" >
注:onclick="this.src=this.src+'?'+Math.random()"意思是点验证码是自已刷新一下.
注:src="{:U('login/selfverify')}" 意思是验证码图的地址是:login控制器下面的selfverify方法
注:src="{:U('login/selfverify')}" 可以用 src="__URL__/selfverify"来代替,效果是一样的

3验证码的校验
在应用的公共模块Application\Common\Common里面的function.php中或自已控制器内写一个校验方法:
function check_verify($code,$id=''){
$verify = new \Think\Verify();
return $verify->check($code,$id);
}

 

php 获取URL地址

来源:http://www.cnblogs.com/A-Song/archive/2011/12/14/2288215.html

#测试网址:     http://localhost/blog/testurl.php?id=5

//获取域名或主机地址 
echo $_SERVER['HTTP_HOST']."<br>"; #localhost

//获取网页地址 
echo $_SERVER['PHP_SELF']."<br>"; #/blog/testurl.php

//获取网址参数 
echo $_SERVER["QUERY_STRING"]."<br>"; #id=5

//获取用户代理 
echo $_SERVER['HTTP_REFERER']."<br>"; 

//获取完整的url
echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
#http://localhost/blog/testurl.php?id=5

//包含端口号的完整url
echo 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; 
#http://localhost:80/blog/testurl.php?id=5

//只取路径
$url='http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]; 
echo dirname($url);
#http://localhost/blog

 

js trim类 去除字符串空格

类方法

//去除左右空格
String.prototype.trim=function(){
   return this.replace(/(^\s*)|(\s*$)/g, "");
}
//去除左空格
String.prototype.ltrim=function(){
   return this.replace(/(^\s*)/g,"");
}
//去除右空格
String.prototype.rtrim=function(){
   return this.replace(/(\s*$)/g,"");
}

函数

function trim(str){ //删除左右两端的空格
       return str.replace(/(^\s*)|(\s*$)/g, "");
   }
   function ltrim(str){ //删除左边的空格
       return str.replace(/(^\s*)/g,"");
   }
   function rtrim(str){ //删除右边的空格
       return str.replace(/(\s*$)/g,"");
   }

 

 

bootstrap js创建模态框

Modal 属性

**m_系列——文字描述、内容类

//模态框抬头标题

Modal.m_title="string";

//模态框内容区域

Modal.m_body="string";//支持html对象

//模态框id

Modal.m_id="string";

**set_系列——执行函数类

//生成模态框底部按钮

Modal.set_btn({"string":callback})//按钮文字、执行函数

**基础系列

//弹出模态框

Modal.create()

//关闭模态框

Modal.close()

//模态框
function CreateModal(){
  this.m_title="默认模态框";
  this.m_body="默认内容";
  this.m_id="newmodal";
  this.m_target="body";
  this.btn=[];
  this.set_btn=function(data){
    var btnarr=[];
    for(var key in data){
      var btn = document.createElement("button");
      btn.className="btn btn-primary";
      btn.onclick=data[key];
      btn.innerHTML=key;
      this.btn.push(btn);
    }
  }
  this.close=function(){
    $(".modal.fade").remove();
    $(".modal-backdrop.fade").remove();
  }
  this.create=function(){
    this.close();
    var modal_block = document.createElement("div");
      modal_block.className = "modal fade";
      modal_block.id = this.m_id;
      modal_block.setAttribute("data-show","true")
      var modal_dialog = document.createElement("div");
        modal_dialog.className="modal-dialog modal-lg";
        var modal_content = document.createElement("div");
          modal_content.className="modal-content";
          var modal_head = document.createElement("div");
            modal_head.className=  "modal-header";
            var btn_close = document.createElement("button");
              btn_close.className="close";
              btn_close.type="button";
              btn_close.innerHTML="&times;";
              btn_close.addEventListener("click",this.close);
            modal_head.appendChild(btn_close);
            var modal_head_p = document.createElement("h4");
              modal_head_p.innerHTML=this.m_title;
            modal_head.appendChild(modal_head_p);
          modal_content.appendChild(modal_head);
          var modal_body = document.createElement("div");
            modal_body.className="modal_body";
            if(typeof(this.m_body)=="string"){
              modal_body.innerHTML=this.m_body;
            }else{
              modal_body.appendChild(this.m_body);
            }
          modal_content.appendChild(modal_body);
          var modal_footer =document.createElement("div");
            modal_footer.className="modal-footer";
            this.btn.map(function(btns,index){
              modal_footer.appendChild(btns);
            })
          modal_content.appendChild(modal_footer);
        modal_dialog.appendChild(modal_content);
      modal_block.appendChild(modal_dialog);

    $(this.m_target).append(modal_block);
    $("#"+this.m_id).modal('show');
  }
}

 

 

chrome扩展 发送ajax请求后储存信息

manifest

{
  "name":"Catch your Data",
  "description":"Catch every data what you need",
  "version":"1.0",
  "permissions": [
    "tabs", "http://*/*", "https://*/*","http://service.miniice.cn/","storage"//storage必须有,储存权限
  ],
  "browser_action": {
      "default_title": "Get this page's Data.",
      "default_icon": "icon.png",
      "default_popup": "popup.html"
  },
  "manifest_version":2,
  "content_scripts": [
    {
      "js":["jquery-2.2.0.min.js","getnumber.js"],
      "matches":["https://sycm.taobao.com/portal/*"]//权限设置,可不设
    }
  ],
  "background": {
        "scripts": ["jquery-2.2.0.min.js","ajax.js"]
    },
  "options_page":"options.html"

}

background - ajax.js

$.post("data.php","",function(ret){
  console.log(ret);
  chrome.storage.sync.set(ret, function(){
      //do something
      console.log("缓存成功")
  });
})

 

content_scripts ?getnumber.js

chrome.storage.sync.get(null,function(result){
      console.log(result);
    })

 

chrome插件 注入js以及发送ajax(message/request)

注入js来源:http://www.2cto.com/article/201307/225986.html

发送ajax来源:http://www.cnblogs.com/onlyfu/p/4458025.html

manifest.json 内容

知识点包含:
* content_scripts注入js,background.scripts用来发送请求(content_scripts禁止发送ajax)
* Message 和 Request 区别

manifest

{
  "name":"Catch your Data",
  "description":"Catch every data what you need",
  "version":"1.0",
  "permissions": [
    "tabs", "http://*/*", "https://*/*","http://service.miniice.cn/"
  ],
  "browser_action": {
      "default_title": "Get this page's Data.",
      "default_icon": "icon.png",
      "default_popup": "popup.html"
  },
  "manifest_version":2,
  "content_scripts": [
    {
      "js":["jquery-2.2.0.min.js","content_script.js"],
      "matches":["https://sycm.taobao.com/portal/*"]
    }
  ],
  "background": {
        "scripts": ["jquery-2.2.0.min.js","background.js"]
    }
}

标签脚本(content_script)和背景页(background)交互可以有多种方式
其中我使用过 Message 和 Request
Message用于立即响应消息,多用于读取早已缓存的信息,不适合异步
Request多用于异步请求服务器

Message 要这么写

content_script.js?内容

var jsonarr={
  'name':'abc'
}
chrome.extension.sendMessage(jsonarr, function(ret){
        console.log(ret);
      });

background.js 内容

chrome.extension.onMessage.addListener(function(objRequest, _, sendResponse){
  var send={
        "data":objRequest,
        "info":"以上是您输入的信息",
        "status":1,
    }
    sendResponse(send);
});

Request 要这么写

content_script.js?内容

var jsonarr={
  'version':'abc123'
}
chrome.extension.sendRequest(jsonarr, function(ret){
        console.log(ret);
      });

background.js 内容

chrome.extension.onRequest.addListener(function(objRequest, _, sendResponse){
    $.post("deal.php",objRequest,function(ret){
        sendResponse(ret);
    })
});