什么是ajax?关于ajax的具体介绍
什么是AJAX?
不刷新页面请求数据
从服务器获取数据
Step 1 – 如何请求
httpRequest.onreadystatechange = nameOfTheFunction;
httpRequest.onreadystatechange = function(){
// Process the server response here.
};
httpRequest.open('GET', 'http://www.example.org/some.file', true);
httpRequest.send();
open() 的第一个参数是HTTP 请求的方法 – GET, POST, HEAD, 或者其他服务器支持的方法。方法名全部大写是http标准,不然有些浏览器(例如:Firefox)可能会不发器请求。 点击 W3C specs 获得更多关于http请求方法的信息。
第二个参数是要请求的url。从安全方面考虑,默认不能跨域请求url。确保所有页面在同一个域名下,不然调用open()方法,你会得到 "permission denied” 错误。 一个常见的跨域是你网站的域名是 domain.tld,但是尝试用 www.domain.tld访问页面。如果真的想跨域请求,查看 HTTP access control。
可选的第三个参数设置这个请求是同步还是异步的。如果是true (默认值), JavaScript 会继续执行,用户操作页面的同时,服务器返回数据。这是 AJAX的A。
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Step 2 – 处理服务器响应
httpRequest.onreadystatechange = nameOfTheFunction;
if (httpRequest.readyState === XMLHttpRequest.DONE) {
// Everything is good, the response was received.
} else {
// Not ready yet.
}
0 (uninitialized) or (请求未初始化)
1 (loading) or (服务器建立连接)
2 (loaded) or (请求被接收)
3 (interactive) or (执行请求)
4 (complete) or (request finished and response is ready请求完成响应到位)
Value State Description 0 UNSENT Client has been created. open() not called yet. 1 OPENED open() has been called. 2 HEADERS_RECEIVED send() has been called, and headers and status are available. 3 LOADING Downloading; responseText holds partial data. 4 DONE The operation is complete.
if (httpRequest.status === 200) {
// Perfect!
} else {
// There was a problem with the request.
// For example, the response may have a 404 (Not Found)
// or 500 (Internal Server Error) response code.
}
httpRequest.responseText – 返回服务器响应字符串
httpRequest.responseXML – 返回服务器响应XMLDocument 对象 可以传递给JavaScript DOM 方法
Step 3 – 一个简单的例子
<button id="ajaxButton" type="button">Make a request</button>
<script>
(function() {
var httpRequest;
document.getElementById("ajaxButton").addEventListener('click', makeRequest);
function makeRequest() {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', 'test.html');
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
用户点击"Make a request” 按钮;
事件调用 makeRequest() 方法;
请求发出,然后 (onreadystatechange)执行传递给 alertContents();
alertContents() 检查响应是否 OK, 然后 alert() test.html 文件内容。
function alertContents() {
try {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
catch( e ) {
alert('Caught Exception: ' + e.description);
}
}
Step 4 – 使用 XML 响应
<?xml version="1.0" ?>
<root>
I'm a test.
</root>
...
onclick="makeRequest('test.xml')">
...
var xmldoc = httpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);
Step 5 – 使用数据返回
<label>Your name:
<input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
document.getElementById("ajaxButton").onclick = function() {
var userName = document.getElementById("ajaxTextbox").value;
makeRequest('test.php',userName);
};
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));
}
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.');
}
}
}
$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
$array = ['userName' => $name, 'computedString' => $computedString];
echo json_encode($array);
以上就是什么是ajax?关于ajax的具体介绍的详细内容,更多请关注其它相关文章!