发送POST请求

来源:互联网 发布:知乎 梵高 被高估 编辑:程序博客网 时间:2024/06/05 01:05

      如上所述,POST请求的适应性更广,可使用更大的请求参数,而且POST请求参数通常不能直接看到。因此在使用Ajax发送请求时,尽量采用POST方式而不是GET方式发送请求。发送POST请求通常需要如下三个步骤:

1.使用open方法打开连接时,指定使用POST方式发送请求。

2.设置正确请求头,POST请求通常应设置Content-Type请求头。

3.发送请求,把请求参数转为查询字符串,将该字符串作为send()方法的参数。

<!DOCTYPE html><html>  <head>    <title>first.html</title>    <meta name="keywords" content="keyword1,keyword2,keyword3">    <meta name="description" content="this is my page">    <meta name="content-type" content="text/html; charset=UTF-8">        <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->  </head>    <body><select name="first" id="first" onchange="change(this.value);"><option value="1" selected="selected">中国</option><option value="2">美国</option><option value="3">日本</option></select><select name="second" id="second"></select><script type="text/javascript">function createXMLHttpRequest(){if(window.XMLHttpRequest){xmlrequest = new XMLHttpRequest();}else if(window.ActiveXObject){try{xmlrequest = new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{xmlrequest = new ActiveXObject("Microsoft.XMLHTTP");}catch(e){}}}}function change(id){createXMLHttpRequest();var uri="second.jsp";xmlrequest.onreadystatechange = processResponse;xmlrequest.open("POST",uri,true);<span style="color:#ff0000;">xmlrequest.setRequestHeader("COntent-Type","application/x-www-form-urlencoded");</span>xmlrequest.send("id="+id);}//回调函数是请求服务器端的页面,由xmlrequest.responseText获取,对其进行处理之后//将处理结果返回到页面中function processResponse(){if(xmlrequest.readyState == 4){if(xmlrequest.status == 200){var cityList = xmlrequest.responseText.split("$");var displaySelect = document.getElementById("second");displaySelect.innerHTML =null;for(var i = 0;i< cityList.length ; i++){var op = document.createElement("option");op.innerHTML = cityList[i];//将新的选项添加到列表框的最后displaySelect.appendChild(op);}}else{//页面不正常window.alert("您所请求的页面有异常.");}}}</script>  </body></html>

0 0
原创粉丝点击