什么是AJAX?
AJAX =异步JavaScript和XML。
ajax的基础是XMLHttpRequest对象。所有现代浏览器支持XMLHttpRequest对象(IE5和IE6使用ActiveXObject对象)。
所有现代浏览器(IE7 +,火狐,Chrome,苹果Safari和Opera)有一个内置的XMLHttpRequest对象。
创建一个XMLHttpRequest对象的语法:
xhr=new XMLHttpRequest();
Internet Explorer (IE5 and IE6) 使用 ActiveX 对象:
xhr=new ActiveXObject(“Microsoft.XMLHTTP”);
创建一个满足所有浏览器的对象:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
响应准备就绪时,指定一个函数获取响应结果与执行操作
xhr.onreadystatechange=function()
{
if (xhr.readyState4 && xhr.status200)
{
函数;(函数名(xhr))
}
}
发送一个请求到服务器
向服务端发送一个请求,XMLHttpRequest对象的open()和send()方法:
xmlhttp.open(“GET”,“ajax.php”,true);
xmlhttp.send();
POST 请求
var xhr = new XMLHttpRequest();
`if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else if(window.ActiveXObject){
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}else{
alert('该浏览器不支持Ajax网络请求!');
}`
2、 xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
doResponse(xhr);
}
}
}
xhr.open(‘POST’,01-reg-ajax.php
,true);
POST请求中的默认Content-Type text/plain PHP服务器会拒绝接受请求数据,
必须在请求消息发送之前进行修改!
xhr.setRequestHeader(‘Content-Type’,‘application/x-www-form-urlencoded’);
get请求:
简单 GET 请求:
xhr.open("GET","demo_get.asp",true);
xhr.send();
如果发送请求时,添加一些参数,可以把参数加到url上
xhr.open(“GET”,“demo_get2.asp?fname=Henry&lname=Ford”,true);
xhr.send();
在php中接受响应
通用:$k = $_REQUEST[‘html中的’];
一定要和HTML传输过来的变量名字一样。
PHP中的数据引用
require(‘data.php’);