原生ajax发送请求:
1.创建xmlhttprequest对象
ie中为activexobject("microsoft.xmlhttp") 早期的ie浏览器
2.准备发送
3.执行发送动作
4.指定回调函数
案例:
1.html文件
初识 ajaxwindow.onload = function(){
var btn = document.getelementbyid('btn');
btn.onclick = function(){
var uname = document.getelementbyid('username').value;
var pw = document.getelementbyid('password').value;
//使用ajax
//1.创建xmlhttprequest对象
var xhr = new xmlhttprequest();
//2.准备发送
xhr.open('get','./check.php?username='+uname+'&password='+pw,true);
//3.执行发送动作
xhr.send(null);
//4.指定回调函数
xhr.onreadystatechange = function(){
if(xhr.readystate == 4){
if(xhr.status == 200){
var data = xhr.responsetext;
var info = document.getelementbyid('info');
if(data == 'ture'){
info.innerhtml = 'success';
}else if(data == 'false'){
info.innerhtml = 'false';
}
}
}
}
}
}
用户名:
密 码:
2.php文件
$uname = $_get['username'];
$pw = $_get['password'];
if($uname == 'admin' && $pw == '123'){
echo 'ture';
}else{
echo "false";
}
?>
1.get
get请求参数在url中传递
2.post
post请求参数在请求体重传递
案例:
1.html
#dv{
width: 360px;
height: 100px;
background-color: green;
position: absolute;
left: 50%;
top: 10px;
margin-left: -180px;
}
/*
*功能:
*页面输入图书编号,查询服务器端的图书信息并解析
*
*/
$(function(){
$('#btn1').click(function(){
var code = $('#code').val();
$.ajax({
type:'get',
url:'02.php',
data:{code:code},
datatype:'json',
success:function(data){
var info = document.getelementbyid('info');
if(data.flag == 0){
info.innerhtml = 'not find book';
}else{
var tag = '
- bookname:'+data.bookname+'
- autor:'+data.autor+'
info.innerhtml = tag;
}
},
error:function(){
$('#info').html('server error');
};
});
});
});
booknumber:
2.php
$code = $_get['code'];
$books = array();
$books['sgyy'] = array('bookname'=>'三国演义','autor'=>'罗贯中');
$books['shz'] = array('bookname'=>'水浒传','autor'=>'施耐庵');
$books['xyj'] = array('bookname'=>'西游记','autor'=>'吴承恩');
$books['hlm'] = array('bookname'=>'红楼梦','autor'=>'曹雪芹');
if(array_key_exists($code, $books) == 1){//判断非空
$book = $books[$code];
echo json_encode($book);
}else{
echo '{"flag":0}';
}
?>
1.静态script标签src属性进行跨域请求
-
-默认为同步请求,加异步请求输入无法加载
-1.必须保证加载的顺序
-2.不方便通过程序传递参数
2.动态创建script标签,通过标签的src属性发送请求(jsonp本质)
-1.动态创建script标签是异步请求
-利用函数调用解决
-服务端响应的内容是函数调用
例如:
var script = document.createelement('script');
script.src = 'http://www.snake.com/ajax/demo/ajax20190403/test.php';
var head = document.getelementsbytagname('head')[0];
head.appendchild(script);
//服务器响应的内容调用
function foo(data){
console.log(data);
}
特此声明:如需转载请注明出处,如有疑问请及时提出以便于改正,如有侵权,联系删除,谢谢