码迷,mamicode.com
首页 > Web开发 > 详细

Ajax基本知识(三)

时间:2016-04-27 20:42:31      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

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 makeRequest() to accept the user data and pass it along to the server. We‘ll change the request method from GET to POST, and include our data as a parameter in the call to httpRequest.send():

 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 way it was in Step 3 to alert our computed string, if that‘s all the server returns. However, let‘s say the server is going to return both the computed string and the original user data. So if our 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 was a problem with the request.‘);
    }
  }
}

 

Ajax基本知识(三)

标签:

原文地址:http://www.cnblogs.com/guojunru/p/5440208.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!