首页 > Web开发 > 详细

Ajax基本知识(三)

时间:2016-04-27 20:42:29      阅读:325      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!