Ajax的使用方法
发布时间:2020-12-16 03:01:45 所属栏目:百科 来源:网络整理
导读:Ajax 一、 javaScript原生使用Ajax 1.get方法 //1.创建对象 兼容处理var xhr = null;//处理低版本IE不兼容问题if(window.XMLHttpRequest){ xhr = new XMLHttpRequest();}else{ xhr = new ActiveXObject("Microsoft.XMLHTTP");}//2.准备发送xhr.open('get','x
Ajax一、 javaScript原生使用Ajax1.get方法//1.创建对象 兼容处理 var xhr = null; //处理低版本IE不兼容问题 if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } //2.准备发送 xhr.open('get','xxx.php?username=' + usernameValue,true); //3.执行发送 xhr.send(null); //4.回调 xhr.onreadystatechange = function () { /*xhr.readyState == 4 是表示数据解析完成,后台处理完成了。 xhr.status == 200 是表示处理的结果是OK的。响应成功*/ if (xhr.readyState == 4){ if(xhr.status == 200){ //返回结果 var result = xhr.responseText; console.log(result); } } }; 2.post方法//#1.创建对象 兼容性 var xhr = null; //处理低版本IE不兼容问题 if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject("Microsoft.XMLHTTP") } //#2.准备发送 xhr.open('post','xxx.php',true); var param = 'phone=' + phoneValue; //设置响应头 xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); //#3.执行发送 xhr.send(param); //#4.回调函数 xhr.onreadystatechange = function () { if(xhr.readyState == 4){ if(xhr.status ==200){ var result = xhr.responseText; console.log(result); } } }
二、 jQuery中的Ajax1.基本使用方法$.ajax({ url: 'xxx.php',type: 'get',beforeSend: function(xhr){ console.log(xhr); },success: function (res) { console.log(res); },error:function (xhr) { console.log(xhr); },complete:function (xhr) { console.log(xhr); } });
2.快捷方式$.get('xxx.php',{id:1},function (res) { console.log(res); }); $.post('xxx.php',function (res) { console.log(res); });
3.解析Json格式$.getJSON('xxx.php',function (res) { console.log(res); });
<?php $zhangsan = array( 'name' =>'张三','age' =>18 ); //格式 header('Content-Type:application/json'); echo json_encode($zhangsan); ?> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |