标签:
<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.‘); } } }
标签:
原文地址:http://www.cnblogs.com/guojunru/p/5440208.html