/*html部分*/
<form>
<p>
<label for="username">用户名</label>
<input id="username" />
</p>
<p>
<label for="id">身份证</label>
<input id="id" />
</p>
<p>
<label for="tel">手机号</label>
<input id="tel" />
</p>
<p>
<input type="button" value="提交" id="btn" />
</p>
</form>
/*js部分*/
//获取表单的值
var btn = document.getElementById("btn"),
username = document.getElementById("username"),
id = document.getElementById("id"),
tel = document.getElementById("tel");
//请求的接口
var url = 'http://localhost:8080/';
//点击提交的时候 get请求
btn.addEventListener("click", function () {
//把需要传的参数 拼接成username=123 &id=233 的格式
var params = 'username=' + username.value + '&id=' + id.value + '&tel=' + tel.value;
var paramsjson = {
username: username.value,
id: id.value,
tel: tel.value
}
console.log(username.value, id.value, tel.value)
console.log("提交")
//ajax的发送请求 函数
// ajaxSbmit('get', params, url);
// ajaxSbmit('POST', params, url);
ajaxSbmit('POST', paramsjson, url, 'json');
})
/*
第一个参数 ajaxWay是请求方式 一般是get 或者post
第二个参数 params是需要给服务器传的参数
第三个个参数 url 是需要请求的接口
*/
function ajaxSbmit(ajaxWay, params, url, jsonWay) { //jsonWay不传的话默认 undefined
console.log(ajaxWay, params, url)
//创建ajax对象
var xhr = new XMLHttpRequest();
//配置ajax对象
if (ajaxWay === 'get') {//get请求方式
xhr.open(ajaxWay, url + ajaxWay + '?' + params);
//发送请求
xhr.send();
} else { //POSt请求方式
//设置请求参数的格式类型(post必须设置) application/json(JSON数据格式)
if (jsonWay === 'json') {
//配置ajax对象
xhr.open(ajaxWay, url + jsonWay);
xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); //JSON格式的请求头
//发送请求
console.log(params)
xhr.send(JSON.stringify(params));
} else {
//配置ajax对象
xhr.open(ajaxWay, url + ajaxWay);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//发送请求
xhr.send(params);
}
}
//等待服务器的响应时间 等待服务器返回内容
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText)
} else {
console.log("出错了:" + xhr.status);
}
}
}
}
原生ajax的请求方式和解析
最新推荐文章于 2023-05-15 11:59:13 发布