AJAX編程實踐之與伺服器通訊

來源:互聯網
上載者:User

首先看下看下相對簡單些的--向伺服器發送一個包含有名/值對的簡單查詢串,在這種情況下XHP即可以用GET也可以用POST。

GET
function doRequestUsingGET() {
 createXMLHttpRequest();
 var queryString = " GetAndPostExample? " ;
 queryString = queryString + createQueryString()+ " &timeStamp= " + new Date().getTime();
 xmlHttp.onreadystatechange = handleStateChange;
 xmlHttp.open( " GET " , queryString, true );
 xmlHttp.send( null );
}
POST
function doRequestUsingPOST() {
 createXMLHttpRequest();
 var url = " GetAndPostExample?timeStamp= " + new Date().getTime();
 var queryString = createQueryString();
 xmlHttp.open( " POST " , url, true );
 xmlHttp.onreadystatechange = handleStateChange;
 xmlHttp.setRequestHeader( " Content-Type " , " application/x-www-form-urlencoded " );
 xmlHttp.send(queryString);
}

queryString就是名/值對的參數形式了(如name=LiLin&age=23),在調用OPEN方法中,當要求方法是用POST的時候為了確保伺服器知道請求體中有請求參數,需要調用setRequestHeader,將Content-Type值設定為application/x-www-form-urlencoded.當然也可不放在請求體中(那就不要用POST啦!)

此時server處理:

import java.io. * ;
import java.net. * ;
import javax.servlet. * ;
import javax.servlet.http. * ;
public class GetAndPostExample extends HttpServlet {
 protected void processRequest(HttpServletRequest request, HttpServletResponse response, String method)
throws ServletException, IOException {
  // Set content type of the response to text/xml
  response.setContentType( " text/xml " );
  // Get the user's input
  String firstName = request.getParameter( " firstName " );
  String middleName = request.getParameter( " middleName " );
  String birthday = request.getParameter( " birthday " );
  // Create the response text
  String responseText = " Hello " + firstName + " " + middleName
+ " . Your birthday is " + birthday + " . "
+ " [Method: " + method + " ] " ;
  // Write the response back to the browser
  PrintWriter out = response.getWriter();
  out.println(responseText);
  // Close the writer
  out.close();
 }
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  // Process the request in method processRequest
  processRequest(request, response, " GET " );
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  // Process the request in method processRequest
  processRequest(request, response, " POST " );
 }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.