@fantaghiro
2014-10-17T09:07:08.000000Z
字数 9278
阅读 1982
js 学习笔记 妙味课堂
什么是Ajax
使用Ajax
<input type="button" value="按钮" id="btn" />
var oBtn = document.getElementById('btn');oBtn.onclick = function(){//打开浏览器/*1. 创建一个ajax对象,并解决兼容性问题*/var xhr = null;if(window.XMLHttpRequest){xhr = new XMLHttpRequest();} else {xhr = new ActiveXObject('Microsoft.XMLHTTP');}/*也有使用以下方式处理兼容性问题try {xhr = new XMLHttpRequest();} catch(e){xhr = new ActiveXObject('Microsoft.XMLHTTP');}*///在地址栏中输入地址/*open方法:参数:1. 打开方式:用get方式还是post方式2. 地址3. 是否异步异步:非阻塞模式(前面的代码不会影响后面代码的执行)同步:阻塞模式(当前面代码没做完时,阻塞后续代码的执行)*/xhr.open('get', '1.txt', true);//提交 发送请求xhr.send();//等待服务器返回内容/*readyState: ajax工作状态:0、1、2、3、4responseText: ajax请求返回的内容就被存放到这个属性下面 字符串类型onreadystatechange:当readyState改变的时候触发status:服务器状态,http状态码*/xhr.onreadystatechange = function(){if(xhr.readyState == 4){if(xhr.status == 200){alert(xhr.responseText);} else {alert('出错了,Error:' + xhr.status);}}}}
try语法:
try {//代码尝试执行这个块中的内容,如果有错误,则会执行catch{}的代码,并且传入一个错误信息参数alert(a);//throwthrow new Error('错了错了'); //即使上面没错,也可以通过throw来手动抛错} catch (e) {alert(e);}
表单
get方式:
<form action="1.get.php"><input type="text" name="username" /><input type="text" name="age" /><input type="submit" value="提交" /></form>
<?phpheader('content-type:text/html;charset="utf-8"');error_reporting(0);$username = $_GET['username'];$age = $_GET['age'];echo "你的名字:{$username},年龄:{$age}";
post方式:
<form action="1.post.php" method="post"><input type="text" name="username" /><input type="text" name="age" /><input type="submit" value="提交" /></form>
<?phpheader('content-type:text/html;charset="utf-8"');error_reporting(0);$username = $_POST['username'];$age = $_POST['age'];echo "你的名字:{$username},年龄:{$age}";
get和post的区别:
后端数据的接收:
$_POST
前后台键名和传输方式必须一致
应用中get和post的区别处理:
get方式传递:
var oBtn = document.getElementById('btn');oBtn.onclick = function(){var xhr = null;if(window.XMLHttpRequest){xhr = new XMLHttpRequest();} else {xhr = new ActiveXObject('Microsoft.XMLHTTP');}/*get方式的两个问题1. 缓存问题:在url?后面连接一个随机数或时间戳2. 传输中文产生乱码:采用编码encodeURI*/xhr.open('get', '2.get.php?username=' + encodeURI('刘伟') + 'o&age=30&' + new Date().getTime() , true);xhr.send();xhr.onreadystatechange = function(){if(xhr.readyState == 4){if(xhr.status == 200){alert(xhr.responseText);} else {alert('出错了,Error:' + xhr.status);}}}}
<?phpheader('content-type:text/html;charset="utf-8"');error_reporting(0);$username = $_GET['username'];$age = $_GET['age'];echo "你的名字:{$username},年龄:{$age}";
post方式传递:
var oBtn = document.getElementById('btn');oBtn.onclick = function(){var xhr = null;if(window.XMLHttpRequest){xhr = new XMLHttpRequest();} else {xhr = new ActiveXObject('Microsoft.XMLHTTP');}xhr.open('post', '2.post.php', true);/*post方式,数据放在send()方法中,作为参数传递post方式要设置请求头,告诉后端发送数据的类型post没有缓存问题,中文也没有乱码问题,所以无需编码。*/xhr.setRequestHeader('content-type', 'application/x-www.form-urlencoded'); //声明发送的数据编码类型xhr.send('username=刘伟&age=30');xhr.onreadystatechange = function(){if(xhr.readyState == 4){if(xhr.status == 200){alert(xhr.responseText);} else {alert('出错了,Error:' + xhr.status);}}}}
<?phpheader('content-type:text/html;charset="utf-8"');error_reporting(0);$username = $_POST['username'];$age = $_POST['age'];echo "你的名字:{$username},年龄:{$age}";
JSON对象
IE7一下不支持JSON对象。可以到json.org上找javascript下面的json2.js包,引入到文件当中。
var arr = [1, 2, 3];var j = {left: 100};alert(JSON.stringify(arr));alert(JSON.stringify(j);
var s1 = '[100, 200, 300]';var a1 = JSON.parse(s1);alert(a1[0]);var s2 = '{"left": 100}'; //注意jons中的key值一定严格用双引号引起来,否则会出错var a2 = JSON.parse(s2);alert(a2.left);
<input type="button" value="按钮" id="btn" /><ul id="ul1"></ul>
<?phpheader('content-type:text/html;charset="utf-8"');error_reporting(0);$news = array(array('title'=>'新闻标题一','date'=>'2014-9-1'),array('title'=>'新闻标题二','date'=>'2014-9-2'),array('title'=>'新闻标题三','date'=>'2014-9-3'),array('title'=>'新闻标题四','date'=>'2014-9-4'),array('title'=>'新闻标题五','date'=>'2014-9-5'),array('title'=>'新闻标题六','date'=>'2014-9-6'),array('title'=>'新闻标题七','date'=>'2014-9-7'),);echo json_encode($news);
oBtn.onclick = function(){var xhr = null;if(window.XMLHttpRequest){xhr = new XMLHttpRequest();} else {xhr = new ActiveXObject('Microsoft.XMLHTTP');}xhr.open('get', 'getList.php', true);xhr.send();//等待服务器返回内容xhr.onreadystatechange = function(){if(xhr.readyState == 4){if(xhr.status == 200){var data = JSON.parse(xhr.responseText);var oUl = document.getElementById('ul1');var html = '';for(var i=0; i<data.length; i++{html += '<li><a href="">' + data[i].title + '</a>[<span>' + data[i].date + '</span>]</li>';}oUl.innerHTML = HTML;} else {alert('出错了,Error:' + xhr.status);}}}}
为以上新闻获取添加一个定时器:
//此处是名为ajax的js文件function ajax(method, url, data, success){var xhr = null;if(window.XMLHttpRequest){xhr = new XMLHttpRequest();} else {xhr = new ActiveXObject('Microsoft.XMLHTTP');}if(method == 'get' && data){url += '?' + data;}xhr.open(method, url, true);if(method == 'get'){xhr.send();} else {xhr.setRequestHeader('content-type', 'application/x-www.form-urlencoded');xhr.send(data);}xhr.onreadystatechange = function(){if(xhr.readyState == 4){if(xhr.status == 200){success && success(xhr.responseText);} else {alert('出错了,Error:' + xhr.status);}}}}
下面的js中引用上面的ajax函数
oBtn.onclick = function(){ajax('get', 'getNews.php', '', function(data){var data = JSON.parse(data);var oUl = document.getElementById('ul1');var html = '';for(var i=0; i<data.length; i++{html += '<li><a href="">' + data[i].title + '</a>[<span>' + data[i].date + '</span>]</li>';}oUl.innerHTML = HTML;});setInterval(function(){ajax('get', 'getNews.php', '', function(data){var data = JSON.parse(data);var oUl = document.getElementById('ul1');var html = '';for(var i=0; i<data.length; i++{html += '<li><a href="">' + data[i].title + '</a>[<span>' + data[i].date + '</span>]</li>';}oUl.innerHTML = HTML;});}, 1000);}
瀑布流有两种展现形式:固定列、非固定列
<ul id="ul1"><li></li><li></li><li></li><li></li></ul>
body { margin: 0; }#ul1 { width: 1080px; margin: 100px auto 0; }li { width: 247px; list-style: none; float: left; margin-right: 10px; }li div { border: 1px solid #000; padding: 10px; margin-bottom: 10px; }li img { width: 225px; display: block; }
<?phpheader('Content-type:text/html; charset="utf-8"');/*API:getPics.php参数cpage:获取数据的页数*/$cpage = isset($_GET['cpage'])?$_GET['cpage']:1;$url = 'http://www.wookmark.com/api/json/popular?page=' . $cpage;$content = file_getcontents($url);$content = iconv('gbk', 'utf-8', $content);echo $content;?>
function ajax(method, url, data, success){var xhr = null;if(window.XMLHttpRequest){xhr = new XMLHttpRequest();} else {xhr = new ActiveXObject('Microsoft.XMLHTTP');}if(method == 'get' && data){url += '?' + data;}xhr.open(method, url, true);if(method == 'get'){xhr.send();} else {xhr.setRequestHeader('content-type', 'application/x-www.form-urlencoded');xhr.send(data);}xhr.onreadystatechange = function(){if(xhr.readyState == 4){if(xhr.status == 200){success && success(xhr.responseText);} else {alert('出错了,Error:' + xhr.status);}}}}window.onload = function(){var oUl = document.getElementById('ul1');var aLi = oUl.getElementsByTagName('li');var iLen = aLi.length;var iPage = 1;var b = true;//初始化数据处理getList();function getList(){ajax('get', 'getPics.php', 'cpage=' + iPage, function(data){var data = JSON.parse(data);if(!data.length){//后续没有数据了return;}for (var i=0; i<data.length; i++){//获取高度最短的livar _index = getShort();var oDiv = document.createElement('div');var oImg = document.createElement('img');oImg.src = data[i].preview;oImg.style.width = '225px';oImg.style.height = data[i].height * (225 / data[i].width) + 'px'; //解决由于图片加载造成的图片位置添加有误的问题,并且解决图片固定宽的宽高比例问题oDiv.appendChild(oImg);var oP = document.createElement('p');oP.innerHTML = data[i].title;oDiv.appendChild(oP);aLi[_index].appendChild(oDiv);}b = true;});}window.onscroll = function(){var _index = getShort();var oLi = aLi[_index];var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;if(getTop(oLi) + oLi.offsetHeight < document.documentElement.clientHeight + scrollTop){if(b){b = false;iPage++;getList();}}}function getShort(){var index = 0;var ih = aLi[index].offsetHeight;for(var i=0; i<iLen; i++){if(aLi[i].offsetHeight < ih){index = i;ih = aLi[i].offsetHeight;}}return index;}function getTop(obj){var iTop = 0;while(obj){iTop += obj.offsetTop;obj = obj.offsetParent;}return iTop;}}
在资源加载进来之前定义好一个函数,这个函数接收一个参数(数据),函数里面利用这么参数做一些事情。
然后需要的时候通过script标签加载对应远程文件资源,当远程文件资源被加载进来的时候,就会去执行我们前面定义好的函数,并且把数据当作这个函数的参数传入进去。