[关闭]
@fantaghiro 2014-10-17T09:07:08.000000Z 字数 9278 阅读 1711

AJAX基础、瀑布流项目开发、留言本实战开发

js 学习笔记 妙味课堂


AJAX基础

Ajax原理

什么是Ajax

使用Ajax

Ajax过程详解

  1. 创建一个ajax对象
    • ie6以上和标准浏览器:new XMLHttpRequest()
    • ie6及以下:new ActiveXObject('Microsoft.XMLHTTP')
  2. open方法
    • 三个参数:
      • 提交方式,相当于form-method
      • 提交地址,相当于form-action
      • 异步(同步)
  3. send方法
    • 发送数据请求,相当于form的submit
  4. 请求状态监控
    • onreadystatechange事件
      • readyState属性:请求状态
        • 0(初始化)还没有调用open()方法
        • 1(载入)已调用send()方法,正在发送请求
        • 2(载入完成)send()方法完成,已收到全部响应内容
        • 3(解析)正在解析响应内容
        • 4(完成)响应内容解析完成,可以在客户端调用了
      • status属性:服务器(请求资源)的状态
      • 返回的内容
        • responseText:返回以文本形式存放的内容
        • responseXML:返回XML形式的内容
  1. <input type="button" value="按钮" id="btn" />
  1. var oBtn = document.getElementById('btn');
  2. oBtn.onclick = function(){
  3. //打开浏览器
  4. /*
  5. 1. 创建一个ajax对象,并解决兼容性问题
  6. */
  7. var xhr = null;
  8. if(window.XMLHttpRequest){
  9. xhr = new XMLHttpRequest();
  10. } else {
  11. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  12. }
  13. /*
  14. 也有使用以下方式处理兼容性问题
  15. try {
  16. xhr = new XMLHttpRequest();
  17. } catch(e){
  18. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  19. }
  20. */
  21. //在地址栏中输入地址
  22. /*
  23. open方法:
  24. 参数:
  25. 1. 打开方式:用get方式还是post方式
  26. 2. 地址
  27. 3. 是否异步
  28. 异步:非阻塞模式(前面的代码不会影响后面代码的执行)
  29. 同步:阻塞模式(当前面代码没做完时,阻塞后续代码的执行)
  30. */
  31. xhr.open('get', '1.txt', true);
  32. //提交 发送请求
  33. xhr.send();
  34. //等待服务器返回内容
  35. /*
  36. readyState: ajax工作状态:0、1、2、3、4
  37. responseText: ajax请求返回的内容就被存放到这个属性下面 字符串类型
  38. onreadystatechange:当readyState改变的时候触发
  39. status:服务器状态,http状态码
  40. */
  41. xhr.onreadystatechange = function(){
  42. if(xhr.readyState == 4){
  43. if(xhr.status == 200){
  44. alert(xhr.responseText);
  45. } else {
  46. alert('出错了,Error:' + xhr.status);
  47. }
  48. }
  49. }
  50. }

try语法:

  1. try {
  2. //代码尝试执行这个块中的内容,如果有错误,则会执行catch{}的代码,并且传入一个错误信息参数
  3. alert(a);
  4. //throw
  5. throw new Error('错了错了'); //即使上面没错,也可以通过throw来手动抛错
  6. } catch (e) {
  7. alert(e);
  8. }

表单

get方式:

  1. <form action="1.get.php">
  2. <input type="text" name="username" />
  3. <input type="text" name="age" />
  4. <input type="submit" value="提交" />
  5. </form>
  1. <?php
  2. header('content-type:text/html;charset="utf-8"');
  3. error_reporting(0);
  4. $username = $_GET['username'];
  5. $age = $_GET['age'];
  6. echo "你的名字:{$username},年龄:{$age}";

post方式:

  1. <form action="1.post.php" method="post">
  2. <input type="text" name="username" />
  3. <input type="text" name="age" />
  4. <input type="submit" value="提交" />
  5. </form>
  1. <?php
  2. header('content-type:text/html;charset="utf-8"');
  3. error_reporting(0);
  4. $username = $_POST['username'];
  5. $age = $_POST['age'];
  6. echo "你的名字:{$username},年龄:{$age}";

get和post的区别:

后端数据的接收:

编写Ajax

应用中get和post的区别处理:

get方式传递:

  1. var oBtn = document.getElementById('btn');
  2. oBtn.onclick = function(){
  3. var xhr = null;
  4. if(window.XMLHttpRequest){
  5. xhr = new XMLHttpRequest();
  6. } else {
  7. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  8. }
  9. /*
  10. get方式的两个问题
  11. 1. 缓存问题:在url?后面连接一个随机数或时间戳
  12. 2. 传输中文产生乱码:采用编码encodeURI
  13. */
  14. xhr.open('get', '2.get.php?username=' + encodeURI('刘伟') + 'o&age=30&' + new Date().getTime() , true);
  15. xhr.send();
  16. xhr.onreadystatechange = function(){
  17. if(xhr.readyState == 4){
  18. if(xhr.status == 200){
  19. alert(xhr.responseText);
  20. } else {
  21. alert('出错了,Error:' + xhr.status);
  22. }
  23. }
  24. }
  25. }
  1. <?php
  2. header('content-type:text/html;charset="utf-8"');
  3. error_reporting(0);
  4. $username = $_GET['username'];
  5. $age = $_GET['age'];
  6. echo "你的名字:{$username},年龄:{$age}";

post方式传递:

  1. var oBtn = document.getElementById('btn');
  2. oBtn.onclick = function(){
  3. var xhr = null;
  4. if(window.XMLHttpRequest){
  5. xhr = new XMLHttpRequest();
  6. } else {
  7. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  8. }
  9. xhr.open('post', '2.post.php', true);
  10. /*
  11. post方式,数据放在send()方法中,作为参数传递
  12. post方式要设置请求头,告诉后端发送数据的类型
  13. post没有缓存问题,中文也没有乱码问题,所以无需编码。
  14. */
  15. xhr.setRequestHeader('content-type', 'application/x-www.form-urlencoded'); //声明发送的数据编码类型
  16. xhr.send('username=刘伟&age=30');
  17. xhr.onreadystatechange = function(){
  18. if(xhr.readyState == 4){
  19. if(xhr.status == 200){
  20. alert(xhr.responseText);
  21. } else {
  22. alert('出错了,Error:' + xhr.status);
  23. }
  24. }
  25. }
  26. }
  1. <?php
  2. header('content-type:text/html;charset="utf-8"');
  3. error_reporting(0);
  4. $username = $_POST['username'];
  5. $age = $_POST['age'];
  6. echo "你的名字:{$username},年龄:{$age}";

JSON对象

IE7一下不支持JSON对象。可以到json.org上找javascript下面的json2.js包,引入到文件当中。

  1. var arr = [1, 2, 3];
  2. var j = {left: 100};
  3. alert(JSON.stringify(arr));
  4. alert(JSON.stringify(j);
  1. var s1 = '[100, 200, 300]';
  2. var a1 = JSON.parse(s1);
  3. alert(a1[0]);
  4. var s2 = '{"left": 100}'; //注意jons中的key值一定严格用双引号引起来,否则会出错
  5. var a2 = JSON.parse(s2);
  6. alert(a2.left);

实例:AJAX的封装

  1. <input type="button" value="按钮" id="btn" />
  2. <ul id="ul1"></ul>
  1. <?php
  2. header('content-type:text/html;charset="utf-8"');
  3. error_reporting(0);
  4. $news = array(
  5. array('title'=>'新闻标题一','date'=>'2014-9-1'),
  6. array('title'=>'新闻标题二','date'=>'2014-9-2'),
  7. array('title'=>'新闻标题三','date'=>'2014-9-3'),
  8. array('title'=>'新闻标题四','date'=>'2014-9-4'),
  9. array('title'=>'新闻标题五','date'=>'2014-9-5'),
  10. array('title'=>'新闻标题六','date'=>'2014-9-6'),
  11. array('title'=>'新闻标题七','date'=>'2014-9-7'),
  12. );
  13. echo json_encode($news);
  1. oBtn.onclick = function(){
  2. var xhr = null;
  3. if(window.XMLHttpRequest){
  4. xhr = new XMLHttpRequest();
  5. } else {
  6. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  7. }
  8. xhr.open('get', 'getList.php', true);
  9. xhr.send();
  10. //等待服务器返回内容
  11. xhr.onreadystatechange = function(){
  12. if(xhr.readyState == 4){
  13. if(xhr.status == 200){
  14. var data = JSON.parse(xhr.responseText);
  15. var oUl = document.getElementById('ul1');
  16. var html = '';
  17. for(var i=0; i<data.length; i++{
  18. html += '<li><a href="">' + data[i].title + '</a>[<span>' + data[i].date + '</span>]</li>';
  19. }
  20. oUl.innerHTML = HTML;
  21. } else {
  22. alert('出错了,Error:' + xhr.status);
  23. }
  24. }
  25. }
  26. }

为以上新闻获取添加一个定时器:

  1. //此处是名为ajax的js文件
  2. function ajax(method, url, data, success){
  3. var xhr = null;
  4. if(window.XMLHttpRequest){
  5. xhr = new XMLHttpRequest();
  6. } else {
  7. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  8. }
  9. if(method == 'get' && data){
  10. url += '?' + data;
  11. }
  12. xhr.open(method, url, true);
  13. if(method == 'get'){
  14. xhr.send();
  15. } else {
  16. xhr.setRequestHeader('content-type', 'application/x-www.form-urlencoded');
  17. xhr.send(data);
  18. }
  19. xhr.onreadystatechange = function(){
  20. if(xhr.readyState == 4){
  21. if(xhr.status == 200){
  22. success && success(xhr.responseText);
  23. } else {
  24. alert('出错了,Error:' + xhr.status);
  25. }
  26. }
  27. }
  28. }

下面的js中引用上面的ajax函数

  1. oBtn.onclick = function(){
  2. ajax('get', 'getNews.php', '', function(data){
  3. var data = JSON.parse(data);
  4. var oUl = document.getElementById('ul1');
  5. var html = '';
  6. for(var i=0; i<data.length; i++{
  7. html += '<li><a href="">' + data[i].title + '</a>[<span>' + data[i].date + '</span>]</li>';
  8. }
  9. oUl.innerHTML = HTML;
  10. });
  11. setInterval(function(){
  12. ajax('get', 'getNews.php', '', function(data){
  13. var data = JSON.parse(data);
  14. var oUl = document.getElementById('ul1');
  15. var html = '';
  16. for(var i=0; i<data.length; i++{
  17. html += '<li><a href="">' + data[i].title + '</a>[<span>' + data[i].date + '</span>]</li>';
  18. }
  19. oUl.innerHTML = HTML;
  20. });
  21. }, 1000);
  22. }

瀑布流项目开发

瀑布流有两种展现形式:固定列、非固定列

  1. <ul id="ul1">
  2. <li></li>
  3. <li></li>
  4. <li></li>
  5. <li></li>
  6. </ul>
  1. body { margin: 0; }
  2. #ul1 { width: 1080px; margin: 100px auto 0; }
  3. li { width: 247px; list-style: none; float: left; margin-right: 10px; }
  4. li div { border: 1px solid #000; padding: 10px; margin-bottom: 10px; }
  5. li img { width: 225px; display: block; }
  1. <?php
  2. header('Content-type:text/html; charset="utf-8"');
  3. /*
  4. API:
  5. getPics.php
  6. 参数
  7. cpage:获取数据的页数
  8. */
  9. $cpage = isset($_GET['cpage'])?$_GET['cpage']:1;
  10. $url = 'http://www.wookmark.com/api/json/popular?page=' . $cpage;
  11. $content = file_getcontents($url);
  12. $content = iconv('gbk', 'utf-8', $content);
  13. echo $content;
  14. ?>
  1. function ajax(method, url, data, success){
  2. var xhr = null;
  3. if(window.XMLHttpRequest){
  4. xhr = new XMLHttpRequest();
  5. } else {
  6. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  7. }
  8. if(method == 'get' && data){
  9. url += '?' + data;
  10. }
  11. xhr.open(method, url, true);
  12. if(method == 'get'){
  13. xhr.send();
  14. } else {
  15. xhr.setRequestHeader('content-type', 'application/x-www.form-urlencoded');
  16. xhr.send(data);
  17. }
  18. xhr.onreadystatechange = function(){
  19. if(xhr.readyState == 4){
  20. if(xhr.status == 200){
  21. success && success(xhr.responseText);
  22. } else {
  23. alert('出错了,Error:' + xhr.status);
  24. }
  25. }
  26. }
  27. }
  28. window.onload = function(){
  29. var oUl = document.getElementById('ul1');
  30. var aLi = oUl.getElementsByTagName('li');
  31. var iLen = aLi.length;
  32. var iPage = 1;
  33. var b = true;
  34. //初始化数据处理
  35. getList();
  36. function getList(){
  37. ajax('get', 'getPics.php', 'cpage=' + iPage, function(data){
  38. var data = JSON.parse(data);
  39. if(!data.length){
  40. //后续没有数据了
  41. return;
  42. }
  43. for (var i=0; i<data.length; i++){
  44. //获取高度最短的li
  45. var _index = getShort();
  46. var oDiv = document.createElement('div');
  47. var oImg = document.createElement('img');
  48. oImg.src = data[i].preview;
  49. oImg.style.width = '225px';
  50. oImg.style.height = data[i].height * 225 / data[i].width + 'px'; //解决由于图片加载造成的图片位置添加有误的问题,并且解决图片固定宽的宽高比例问题
  51. oDiv.appendChild(oImg);
  52. var oP = document.createElement('p');
  53. oP.innerHTML = data[i].title;
  54. oDiv.appendChild(oP);
  55. aLi[_index].appendChild(oDiv);
  56. }
  57. b = true;
  58. });
  59. }
  60. window.onscroll = function(){
  61. var _index = getShort();
  62. var oLi = aLi[_index];
  63. var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  64. if(getTop(oLi) + oLi.offsetHeight < document.documentElement.clientHeight + scrollTop){
  65. if(b){
  66. b = false;
  67. iPage++;
  68. getList();
  69. }
  70. }
  71. }
  72. function getShort(){
  73. var index = 0;
  74. var ih = aLi[index].offsetHeight;
  75. for(var i=0; i<iLen; i++){
  76. if(aLi[i].offsetHeight < ih){
  77. index = i;
  78. ih = aLi[i].offsetHeight;
  79. }
  80. }
  81. return index;
  82. }
  83. function getTop(obj){
  84. var iTop = 0;
  85. while(obj){
  86. iTop += obj.offsetTop;
  87. obj = obj.offsetParent;
  88. }
  89. return iTop;
  90. }
  91. }

AJAX-跨域解决之JSONP

在资源加载进来之前定义好一个函数,这个函数接收一个参数(数据),函数里面利用这么参数做一些事情。

然后需要的时候通过script标签加载对应远程文件资源,当远程文件资源被加载进来的时候,就会去执行我们前面定义好的函数,并且把数据当作这个函数的参数传入进去。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注