JS implementation of Ajax POST request steps

Source: Internet
Author: User

The POST request step is not the same as the GET request step in the previous article, just adds

Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");

Here directly on the code:

Two files were created in Web\02_testpost posttest.jsp and Test.js

<%@ Page Language="Java"pageencoding="Utf-8"%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en"><HTML>  <Head>     <Scripttype= "Text/javascript"src= "./test.js"></Script>  </Head>  <Body>     <formAction=""enctype= "application/x-www-form-urlencoded">          <inputtype= "button"name= "OK"ID= "OK"value= "Test Server connection">      </form>  </Body></HTML>

//when the page has finished loading, execute the following codeWindow.onload =function () {document.getElementById ("OK"). onclick =function () {/** 1 Creating XMLHttpRequest Objects*/var xhr=ajaxfunction (); /** 2 server responds request to Browser * * The ReadyState property represents the current state of the AJAX request.                Its value is represented by a number. 0 represents uninitialized. The Open Method 1 is not yet called to indicate that it is loading. The open method has been called, but the Send method has not yet been called 2 to indicate that the load is complete. Send has been called. The request has started 3 for the interaction. The server is sending a response of 4 on behalf of completion.                The response has been sent. Common status codes and their meanings: 404 Page Not Found (not found) 403 Forbidden (Forbidden) 500 Internal server error (internal service error) 2001 cut OK (OK) 304 not modified (not modified) (server returns 304 status , indicating that the source file has not been modified)*/Xhr.onreadystatechange=function () {alert (xhr.readystate); //alert (xhr.status);            if(xhr.readystate==4){                if(xhr.status==200| | xhr.status==304) {var data=Xhr.responsetext;                alert (data); }            }         }                /** 3 The browser establishes a connection with the server * * Xhr.open (method, URL, asynch);         * * Connect with Server using * method: Request type, string similar to "GET" or "POST". * URL: A path string that points to the file on the server you requested.         Request Path * * Asynch: Indicates whether the request is to be transmitted asynchronously, the default value is True (async). */Xhr.open ("POST", ".. /testservlet?timestamp= "+NewDate (). GetTime () + "&c=18",true); //if it is a POST request, set the request header informationXhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); /** 4 Browser sends request to server * * Send () method: * * If the type of the browser request is a get type, the request data is sent via the Send () method, Server could not receive * * If the browser requests a type of post type, send the request data through the Send () method, the server can receive*/Xhr.send ("A=6&b=9");//xhr.send (null);}}function ajaxfunction () {var xmlHttp; Try{//Firefox, Opera 8.0+, Safarixmlhttp=NewXMLHttpRequest (); }    Catch(e) {Try{//Internet Explorerxmlhttp=NewActiveXObject ("Msxml2.xmlhttp"); }        Catch(e) {Try{xmlHttp=NewActiveXObject ("Microsoft.XMLHTTP"); }          Catch(e) {}}} returnxmlHttp;}
 PackageCom.servlet;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjava.io.IOException;ImportJava.io.PrintWriter;/*** Created by Huangyichun on 2016/12/7.*/@WebServlet (Name= "Testservlet", Urlpatterns = "/testservlet") Public classTestservletextendsHttpServlet {protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {System.out.println ("A=" + request.getparameter ("a")); System.out.println ("C=" + request.getparameter ("C")); PrintWriter out=Response.getwriter (); Out.println ("Get Connection Server Success"); }    protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {System.out.println ("Connection ..."); System.out.println ("A=" + request.getparameter ("a")); System.out.println ("C=" + request.getparameter ("C")); PrintWriter out=Response.getwriter (); Out.println ("Get Connection Server Success"); }}

JS implementation of Ajax POST request steps

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.