mysql数据库与前端交互过程_前端html,后端php,数据库mysql 之间的交互

document.onclick = function(){

ajax({

// type:"get", //发送方式,可选,默认get

url:"http://localhost/ajax/php/index.php", //要请求的地址,必选

success:function(res){ //请求成功之后的函数,必选

console.log(res)

},

data:{ //要发送的数据,可选,默认不发

user:"admin",

pass:13123121123

},

// error:function(res){ //请求失败之后的函数,可选,默认不处理

// console.log(res)

// },

// timeout:10 //请求超时的时间,可选,默认2000

})

}

function ajax(options){

// 1.处理默认参数

var {type,url,success,error,data,timeout} = options;

type = type || "get";

data = data || {};

timeout = timeout || 2000;

// 2.解析要发送的数据

var str = "";

for(var i in data){

str += `${i}=${data[i]}&`;

}

// 3.根据方式,决定是否处理url

if(type == "get"){

var d = new Date();

url = url + "?" + str + "__qft=" + d.getTime();

}

// 4.开启ajax

var xhr = new XMLHttpRequest();

// 注意:open中的方式

xhr.open(type,url,true);

xhr.onreadystatechange = function(){

if(xhr.readyState == 4 && xhr.status == 200){

// 5.执行成功之前,先判断是否传入

success && success(xhr.responseText);

// 成功之后,不应有失败

error = null;

}else if(xhr.readyState == 4 && xhr.status != 200){

// 6.执行失败之前,先判断是否传入

error && error(xhr.status);

// 失败之后,不应有成功

success = null;

// 且失败不应多次执行

error = null;

}

}

// 7.如果请求超时,执行失败

setTimeout(() => {

error && error("timeout");

// 失败之后,不应有成功

success = null;

}, timeout);

// 8.最后根据type的方式,决定send的发送内容和格式

if(type == "post"){

xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");

xhr.send(str)

}else{

xhr.send()

}

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值