Ajax Basics (iii)

Source: Internet
Author: User

Step 3–a Simple Example
<label>your Name:   <input type= "text" id= "Ajaxtextbox"/></label><span id= "AjaxButton" style = "Cursor:pointer; Text-decoration:underline "> Make  a request</span>

Get the user ' s data from the text box and send it to the makeRequest() function along with the URL of our server-side script:

  document.getElementById ("Ajaxbutton"). onclick = function () {       var userName = document.getElementById ("Ajaxtextbox "). Value;      MakeRequest (' test.php ', userName);   };

We need to modify to makeRequest() accept the user data and pass it along to the server. We'll change the "request method from GET POST " to "and" include our data as a parameter in the httpRequest.send() "call to:

function makerequest (URL, userName) {    ...    Httprequest.onreadystatechange = alertcontents;    Httprequest.open (' POST ', url);    Httprequest.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded ');    Httprequest.send (' username= ' + encodeuricomponent (userName));  }

The function alertContents() can be written the same-it is in Step 3 to alert we computed string, if that's all the server ret Urns. However, let's say the server is going to return both the computed string and the original user data. So if we have user typed "Jane" in the text box, the server's response would look like this:

{"userData":"Jane","computedString":"Hi, Jane!"}

To use this data within alertContents() , we can ' t just alert the responseText , we have to parse it and alert computedString , the property we want:

function alertcontents () {  if (httprequest.readystate = = = Xmlhttprequest.done) {    if (httprequest.status = = = 200 ) {      var response = Json.parse (httprequest.responsetext);      alert (response.computedstring);    } else {      alert (' There is a problem with the request ');}    }  

Ajax Basics (iii)

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.