1. 程式人生 > >四種 post 請求格式的XMLHttpRequest 寫法

四種 post 請求格式的XMLHttpRequest 寫法

<!DOCTYPE html>
<head>
    <head>
        <meta charset="UTF-8">
        <script>
	function send(type){
		url="http://127.0.0.1:8080/"
		xhr=new XMLHttpRequest();
		xhr.open("post",url,true);
		var data
		if(type=="formdata"){
			data=new FormData();
			data.append("key","value"
); }else if(type=="json"){ xhr.setRequestHeader("Content-Type","application/json"); data=JSON.stringify({"key":"value"}); }else if(type=="text"){ data="key=value"; }else if(type=="www"){ // 這個header 其實是 傳統post 表單的格式 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"
); data="key=value"; } xhr.send(data); }
</script> </head> <body> <div> <input type="button" onclick="send('formdata')" value="FormData"> <br/> <input type="button" onclick="send('json')" value="application/json"> <br/> <
input
type="button" onclick="send('text')" value="text">
<br/> <input type="button" onclick="send('www')" value="application/x-www-form-urlencoded"> <div> </body> </head>