1. 程式人生 > >javascript傳送get、post http請求

javascript傳送get、post http請求

1. 獲得XMLHttpRequest物件

function createXMLHttpRequest() {
	var xmlHttp;
	if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
		if (xmlHttp.overrideMimeType)
			xmlHttp.overrideMimeType('text/xml');
	} else if (window.ActiveXObject) {
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
			}
		}
	}
	return xmlHttp;
}

2. 傳送get請求
    xmlHttp = createXMLHttpRequest();
    var url = "getfiledetail.jsp?fileid="+id;
    xmlHttp.open("GET", url, true);// 非同步處理返回 
    xmlHttp.onreadystatechange = callback; 
    xmlHttp.setRequestHeader("Content-Type",
            "application/x-www-form-urlencoded;");
    xmlHttp.send();

3. 傳送post請求

    var url = "getNginxStatus";
    xmlHttp.open("POST", url, true);
    xmlHttp.onreadystatechange = getStatusBack;
    xmlHttp.setRequestHeader("Content-Type",
	   "application/x-www-form-urlencoded;");
    xmlHttp.send(xml);

ps.額外小功能

1.  網頁顯示xml的標籤:<xmp></xmp>

2.  input標籤onclick傳參:

onclick='onclickfunction("String1","String2");'

不過傳的是常量……