本文實例講述了JS使用post提交的兩種方式。分享給大家供大家參考,具體如下:
第一種提交post的方式是傳統方式,判斷浏覽器進行post請求。
<SCRIPT stype=text/javascript>
var xmlobj; //定義XMLHttpRequest對象
function CreateXMLHttpRequest()
{
if(window.ActiveXObject)
//如果當前浏覽器支持Active Xobject,則創建ActiveXObject對象
{
//xmlobj = new ActiveXObject("Microsoft.XMLHTTP");
try {
xmlobj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlobj = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlobj = false;
}
}
}
else if(window.XMLHttpRequest)
//如果當前浏覽器支持XMLHttp Request,則創建XMLHttpRequest對象
{
xmlobj = new XMLHttpRequest();
}
}
function SubmitArticle(act,cityname,antique) //主程序函數
{
CreateXMLHttpRequest(); //創建對象
//var parm = "act=firstweather" ;//構造URL參數
//antique = escape(antique);
var parm = "act=" + act + "&cityname=" + cityname + "&antique=" + antique;//構造URL參數
//xmlobj.open("POST", "{dede:global.cfg_templeturl/}/../include/weather.php", true); //調用weather.php
xmlobj.open("POST", "/weather/include/weather.php", true); //調用weather.php
xmlobj.setRequestHeader("cache-control","no-cache");
xmlobj.setRequestHeader("contentType","text/html;charset=uft-8") //指定發送的編碼
xmlobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;"); //設置請求頭信息
xmlobj.onreadystatechange = StatHandler; //判斷URL調用的狀態值並處理
xmlobj.send(parm); //設置為發送給服務器數據
}
第二種方式則是虛擬表單的形式提交post請求
function post(URL, PARAMS) {
var temp = document.createElement("form");
temp.action = URL;
temp.method = "post";
temp.style.display = "none";
for (var x in PARAMS) {
var opt = document.createElement("textarea");
opt.name = x;
opt.value = PARAMS[x];
// alert(opt.name)
temp.appendChild(opt);
}
document.body.appendChild(temp);
temp.submit();
return temp;
}
調用方法 如:
復制代碼 代碼如下:post('pages/statisticsJsp/excel.action', {html :prnhtml,cm1:'sdsddsd',cm2:'haha'});
希望本文所述對大家JavaScript程序設計有所幫助。