MangoCool

异步请求中设置自定义headers(javascript和jquery)

2018-07-16 17:21:23   作者:MangoCool   来源:MangoCool

javascript XMLHttpRequest:

function delUser(username, pwd) {
	
	var timestamp = dateFtt("yyyyMMddhhmmss",new Date());

	var xhr = new XMLHttpRequest();
	//设置xhr请求的超时时间
	xhr.timeout = 3000;
	//设置响应返回的数据格式
	xhr.responseType = "json";
	//创建一个 post 请求,采用异步
	xhr.open('POST', "https://localhost/restful/mangocool/deleteUser", true);
	xhr.setRequestHeader("Content-Type","application/json;charset=utf-8");
	xhr.setRequestHeader("X-Resquested-With","XMLHttpRequest");
	xhr.setRequestHeader("Accept","application/json, text/javascript");
	xhr.setRequestHeader('version', '3');
	xhr.setRequestHeader('timestamp', timestamp);
	xhr.send(JSON.stringify({"username":username, "pwd":pwd}));
	xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
        else {
            alert(xhr.statusText);
        }
    }

}
jquery ajax:
function delUser(username, pwd) {
	
	var timestamp = dateFtt("yyyyMMddhhmmss",new Date());

	$.ajax({
		url: "https://localhost/restful/mangocool/deleteUser",
		headers: {"version":"3", "timestamp":timestamp},
		data: JSON.stringify({"username":username, "pwd":pwd}),
		type: "POST",
		dataType: "json",
		contentType: "application/json;charset=utf-8",
		beforeSend: function() {
			// 打开忽略服务器证书
		},
		error: function() {
			alert("","用户删除失败!");
		},
		success: function(res) {
			resFlag = true;
			if(res.respCode == 1) {
				alert("", "用户删除成功!");
			} else {
				alert("", res.respDesc);
			}
		}, 
		complete:function() {
			// 关闭忽略服务器证书
		}
	});
}


还有一个待解决的问题,XMLHttpRequest方式,控制台报错:

InvalidStateError: responseText is only available if responseType is '', 'document', or 'moz-chunked-text'.

看起来是解析json串出错了,ajax没有这个问题。


参考来源:

http://www.w3school.com.cn/xml/xml_http.asp

http://www.w3school.com.cn/jquery/ajax_ajax.asp

标签: javascript jquery 异步 ajax XMLHttpRequest

分享:

上一篇升级mysql-connector 5到8遇到的问题

下一篇ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...

关于我

崇尚极简,热爱技术,喜欢唱歌,热衷旅行,爱好电子产品的一介码农。

座右铭

当你的才华还撑不起你的野心的时候,你就应该静下心来学习,永不止步!

人生之旅历途甚长,所争决不在一年半月,万不可因此着急失望,招精神之萎葸。

Copyright 2015- 芒果酷(mangocool.com) All rights reserved. 湘ICP备14019394号

免责声明:本网站部分文章转载其他媒体,意在为公众提供免费服务。如有信息侵犯了您的权益,可与本网站联系,本网站将尽快予以撤除。