AJAX篇(一) <Prototype>

本文详细介绍了 Prototype JavaScript 库的功能和使用方法,包括实用工具方法、AJAX 请求处理、数组操作、类创建及元素操作等内容。

最新版的prototype是1.5,查了一下有关prototype的资料,发现它的API docs整的不错,写的很清楚,那就不多
说了,依葫芦划瓢,照翻一点吧 http://www.prototypejs.org/api

第一章. Utility Methods
1. $
  $() 相当于 document.getElementById()
  例如以下两行相等:
  Element.hide('itemId');
  $('itemId').hide();
  下面两行也相等:
  ['item1', 'item2', 'item3'].each(Element.hide);
  $('item1', 'item2', 'item3').invoke('hide');  

xml 代码
  1. <HTML>  
  2.  <head>  
  3.   <title>test prototype.js title>  
  4.   <script src='prototype.js'>  
  5.   script>  
  6.  head>  
  7.  <body>  
  8.   test here   
  9.   <div id='div1'>  
  10.    <a href='http://clarancepeng.javaeeye.com' target='_blank'>clarancepeng blog a>  
  11.    nothing   
  12.   div>  
  13.   <form name='testform'>  
  14.    <input type='button' name='testP' onclick='alert($("div1").innerHTML)' value='test prototype'>  
  15.   form>  
  16.      
  17.  body>  
  18. HTML>  


  
2. $$
  $$(cssRule...) -> [HTMLElement...]
  $$ 相当于 document.getElementsByTagName() 或者 document.getElementsByClassName()  
  例:
  $$('div')
  // -> all DIVs in the document. Same as document.getElementsByTagName('div')!
  $$('#contents')
  // -> same as $('contents'), only it returns an array anyway.
  $$('li.faux')
  // -> all LI elements with class 'faux'
  $$('#contents a[rel]')
  // -> all links inside the element of ID "contents" with a rel attribute
  $$('a[href="#"]')
  // -> all links with a href attribute of value "#" (eyeew!)
  $$('#navbar li', '#sidebar li')
  // -> all links within the elements of ID "navbar" or "sidebar"  
  
3. $A
  $A(iterable) -> actualArray
  它能返回数组,$$不能
  var paras = $A(document.getElementsByTagName('p'));
  paras.each(Element.hide);
  $(paras.last()).show();
  
  $A(document.getElementsByTagName('p')).map(Element.extend).invoke('hide');
  
  // The hard way...
  function showArgs() {
  alert(Array.prototype.join.call(arguments, ', '));
  }
  // The easy way...
  function showArgs() {
  alert($A(arguments).join(', '));
  } 
  
4. $F
  $F(element) -> value
  

5. $H


 
 
 

6. $R 返回数组, exclusion默认值为false包含start, end
$R(start, end[, exclusive = false]) -> ObjectRange

7. $W 转换字符串成数组, 有点类似split
$w(String) -> Array
$w('apples bananas kiwis')
// -> ['apples', 'bananas', 'kiwis']

$w("apples bananas kiwis")[0]

8. Try.these 有点类似 try {} catch(e) { }, 返回内部涵数的第一个结果
Try.these(Function...) -> firstOKResult

getTransport: function() {
return Try.these(
function() { return new XMLHttpRequest() },
function() { return new ActiveXObject('Msxml2.XMLHTTP') },
function() { return new ActiveXObject('Microsoft.XMLHTTP') }
) || false;
}

9. document.getElementsByClassName 返回用相同CSS修饰的元素
 document.getElementsByClassName(className[, element]) -> [HTMLElement...]

 

Single class name

Multiple class names


  • List item 1
  • List item 2
  • List item 3


document.getElementsByClassName('foo');
// -> [HTMLElement, HTMLElement] (div#one, div#two)
document.getElementsByClassName('thud');
// -> [HTMLElement, HTMLElement, HTMLElement] (div#two, li#item_one, li#item_two);
document.getElementsByClassName('thud', $('list'));
// -> [HTMLElement, HTMLElement] (li#item_one, li#item_two)

 

第二章 AJAX

1. 公用的选项(Common options)
   选项 : 默认值 : 描述
   asynchronous : true : 决定XMLHttpRequest是同步还是异步, 一般只允许用异步
   contentType : 'application/x-www-form-urlencoded' : 你请求的Content-Type头类型, 如果想发送XML则需要改变这个值
   encoding : 'UTF-8' : 最好保留不变
   method : 'post' : 内容提交的方式, 也可以以'get'方式提交
   parameters : '' : 编码成URL的参数, 以get方式提交
   postBody : None : 以post方式提交时, 提交的内容, 如果没有指定, 则用parameters内容代替
   requestHeaders : : 省略了, 用时再看

2. 公用的回调
   回调方法 : 描述
   onComplete : request完成的时候调用
   onException : 如果有XHR错误产生的时候调用
   onFailure : 请求完成, 并且状态码不是 2xy时调用
   onInteractive : 交换过程中, 正在响应, 发送一部分包过来了, 但是没有最后结束
   onLoaded : XHR对象被设置, 连接被开放, 并且准备发送request时
   onLoading : XHR对象正在被设置, 并且连接打开
   onSuccess : 请求完成, 并且返回状态是 2xy, 发生在onComplete之前
   onUninitialized : 发生在XHR对象刚好创建的时候
   onXYZ : XYZ是响应的返回的状态码, 在响应刚好完成时调用, 不过它会阻止onSuccess/ onFailure的调用, 发生在onComplete之前

3. 响应者的回调
   onCreate
   onComplete
   onException
   onInteractive
   onLoaded
   onLoading
   onUninitialized

4. Ajax.PeriodicalUpdater 定期的调用这个方法, 根据请求得到的数据更新显示的内容
   new Ajax.PeriodicalUpdater(container, url[, options])

 new Ajax.PeriodicalUpdater('items', '/items', {
 method: 'get', frequency: 3, decay: 2
 });

5. Ajax.Request 初始化并且处理一个AJAX请求
   new Ajax.Request(url[, options])

 var url = '/proxy?url=' + encodeURIComponent('http://www.google.com/search?q=Prototype');
 // notice the use of a proxy to circumvent the Same Origin Policy.
 new Ajax.Request(url, {
 method: 'get',
 onSuccess: function(transport) {
 var notice = $('notice');
 if (transport.responseText.match(/href="http:\/\/prototypejs.org/))
 notice.update('Yeah! You are in the Top 10!').setStyle({ background: '#dfd' });
 else
 notice.update('Damn! You are beyond #10...').setStyle({ background: '#fdd' });
 }
 });

6. Request life-cycle
   1) XMLHttpRequest 定义的生命周期
   1. Created
   2. Initialized
   3. Request sent
   4. Response being received (can occur many times, as packets come in)
   5. Response received, request complete

   2) Prototype的AJAX定义的生命周期
   1. onCreate (this is actually a callback reserved to AJAX global responders)
   2. onUninitialized (maps on Created)
   3. onLoading (maps on Initialized)
   4. onLoaded (maps on Request sent)
   5. onInteractive (maps on Response being received)
   6. onXYZ (numerical response status code), onSuccess or onFailure (see below)
   7. onComplete
  
   // This is too bad, there's better!
   new Ajax.Request('/your/url', {
   onComplete: function(transport) {
   if (200 == transport.status)
   // yada yada yada
   }
   });

   new Ajax.Request('/your/url', {
   onSuccess: function(transport) {
   // yada yada yada
   }
   });

7. 取得HTTP 响应头
   var myRequest = new Ajax.Request('/your/url', {
   onSuccess: function() {
   // Note how we brace against null values
   if ((myRequest.getHeader('Server') || '').match(/Apache/))
   ++gApacheCount;
   // Remainder of the code
   }
   });

8. 返回JSON头
   new Ajax.Request('/your/url', {
   onSuccess: function(transport, json) {
   // Remainder of the code
   }
   });

9. Ajax.Responders (AJAX请求的每个步骤的监听通知, 它是整个监听头端)
   Ajax.Responders.register(responder)
   Ajax.Responders.unregister(responder)

   Ajax.Responders.register({
   onCreate: function() {
   Ajax.activeRequestCount++;
   },
   onComplete: function() {
   Ajax.activeRequestCount--;
   }
   });

10. Ajax.Updater
   new Ajax.Updater(container, url[, options])

   new Ajax.Updater('items', '/items', {
   parameters: { text: $F('text') }
   });

   new Ajax.Updater('items', '/items', {
   parameters: { text: $F('text') },
   insertion: Insertion.Bottom
   });

   new Ajax.Updater({ success: 'items', failure: 'notice' }, '/items', {
   parameters: { text: $F('text') },
   insertion: Insertion.Bottom
   });

第三章 数组(Array)

1. 一个数组的遍历
You can revert to vanilla loops:
for (var index = 0; index < myArray.length; ++index) {
var item = myArray[index];
// Your code working on item here...
}
Or you can use iterators, such as each :
myArray.each(function(item) {
// Your code working on item here...
});

2. clear 清空数组
clear() -> Array
var guys = ['Sam', 'Justin', 'Andrew', 'Dan'];
guys.clear();
// -> []
guys
// -> []

3. clone 数组克容
var fruits = ['Apples', 'Oranges'];
var myFavs = fruits.clone();
myFavs.pop();
// fruits -> ['Apples', 'Oranges']
// myFavs -> ['Apples']

4. compact 压缩数组中的''/null项
['frank', , 'sue', , 'sally', null].compact()
// -> ['frank', 'sue', 'sally']

5. each 遍历数组

6. first 数组的第一个值
['Ruby', 'Php', 'Python'].first()
// -> 'Ruby'
[].first()
// -> undefined

7. flatten 压平数组项
['frank', ['bob', 'lisa'], ['jill', ['tom', 'sally']]].flatten()
// -> ['frank', 'bob', 'lisa', 'jill', 'tom', 'sally']

8. from Array.from()是$A的别名
Array.from(iterable) -> actualArray

9. indexOf 当前值在数组中的位置
[3, 5, 6, 1, 20].indexOf(1)
// -> 3
[3, 5, 6, 1, 20].indexOf(90)
// -> -1
[0, false, 15].indexOf(false)
// -> 0 instead of 1, because 0 == false!

10. inspect
['Apples', {good: 'yes', bad: 'no'}, 3, 34].inspect()
// -> "['Apples', [object Object], 3, 34]"

11. last 数组的最后一个值
['Ruby', 'Php', 'Python'].last()
// -> 'Python'
[].last()
// -> undefined

12. reduce 数组只有一个元素就返回这个元素的值, 否则就返回这个数组
reduce() -> Array | singleValue
[3].reduce(); // -> 3
[3, 5].reduce(); // -> [3, 5]

13. reverse 数组中的元素反转
reverse([inline = true]) -> Array

var nums = [3, 5, 6, 1, 20];
nums.reverse(false) // -> [20, 1, 6, 5, 3]
nums // -> [3, 5, 6, 1, 20]
nums.reverse() // -> [20, 1, 6, 5, 3]
nums // -> [20, 1, 6, 5, 3]

14. size
size() -> Number
数组的长度

15. toArray 产生一个新的数组, 类似于clone

16. uniq 去掉数组中的重复项
uniq() -> newArray
['Sam', 'Justin', 'Andrew', 'Dan', 'Sam'].uniq();
// -> ['Sam', 'Justin', 'Andrew', 'Dan']
['Prototype', 'prototype'].uniq();
// -> ['Prototype', 'prototype'] because String comparison is case-sensitive

17. without 去掉数组中的某一项
without(value...) -> newArray
[3, 5, 6, 1, 20].without(3)
// -> [5, 6, 1, 20]
[3, 5, 6, 1, 20].without(20, 6)
// -> [3, 5, 1]

第四章 Class
create
create() -> Function

var Animal = Class.create();
Animal.prototype = {
initialize: function(name, sound) {
this.name = name;
this.sound = sound;
},
speak: function() {
alert(name + " says: " + sound + "!");
}
};
var snake = new Animal("Ringneck", "hissssssssss");
snake.speak();
// -> alerts "Ringneck says: hissssssssss!"
var Dog = Class.create();
Dog.prototype = Object.extend(new Animal(), {
initialize: function(name) {
this.name = name;
this.sound = "woof";
}
});
var fido = new Dog("Fido");
fido.speak();
// -> alerts "Fido says: woof!"

第五章 Element

<div id="message" class=""></div>
// Toggle the CSS class name of div#message
$('message').addClassName('read');
// -> div#message
// You could also use a syntactic-sugar-free version:
Element.toggleClassName('message', 'read');
// -> div#message

$('message').addClassName('read').update('I read this message!').setStyle({opacity: 0.5});

1. addClassName 为某个id增加css的class
<div id="mutsu" class="apple fruit"></div>
$('mutsu').addClassName('food')
$('mutsu').className
// -> 'apple fruit food'
$('mutsu').classNames()
// -> ['apple', 'fruit', 'food']

2. addMethods
addMethods([methods])
$(element).myOwnMethod([args...]);
Element.myOwnMethod(element|id[, args...]);

Element.addMethods({
wrap: function(element, tagName) {
element = $(element);
var wrapper = document.createElement('tagName');
element.parentNode.replaceChild(wrapper, element);
wrapper.appendChild(element);
return Element.extend(wrapper);
}
});

//增加方法
Element.addMethods({
ajaxUpdate: function(element, url, options){
element = $(element);
element.update('<img src="/images/spinner.gif" alt="loading..." />');
new Ajax.Updater(element, url, options);
return element;
}
});
//更新内容
$(element).ajaxUpdate('/new/content');
// -> HTMLElement

//等待信息返回的实现
Form.Element.Methods.processing = function(element, text) {
element = $(element);
if (element.tagName.toLowerCase() == 'input' && ['button', 'submit'].include(element.type))
element.value = typeof text == 'undefined' ? 'Please wait...' : text;
return element.disable();
};
Element.addMethods();

2. ancestors 返回上级标签数组

xml 代码
  1. <html>  
  2. […]   
  3. <body>  
  4. <div id="father">  
  5. <div id="kid">  
  6. </div>  
  7. </div>  
  8. </body>  
  9. </html>  


$('kid').ancestors();
// -> [div#father, body, html] // Keep in mind that
// the `body` and `html` elements will also be included!
document.getElementsByTagName('html')[0].ancestors();
// ->

3. classNames返回修饰的css的class名
classNames(element) -> [className...]
$('mutsu').classNames()
// -> ['apple', 'fruit', 'food']
// change its class names:
$('mutsu').className = 'fruit round'
$('mutsu').classNames()
// -> ['fruit', 'round']

4. cleanWhitespace 移除元素间无用的空格
cleanWhitespace(element) -> HTMLElement

  1. <ul id="apples">  
  2. <li>Mutsu</li>  
  3. <li>McIntosh</li>  
  4. <li>Ida Red</li>  
  5. </ul>  

var element = $('apples');
element.firstChild.innerHTML;
// -> undefined
element.cleanWhitespace();
element.firstChild.innerHTML;
// -> 'Mutsu'

 

xml 代码
内容概要:本文介绍了套针对智能穿戴设备的跑步/骑行轨迹记录系统实战方案,旨在解决传统运动APP存在的定位漂移、数据断层和路径分析单等问题。系统基于北斗+GPS双模定位、惯性测量单元(IMU)和海拔传感器,实现高精度轨迹采集,并通过卡尔曼滤波算法修正定位误差,在信号弱环境下利用惯性导航补位,确保轨迹连续性。系统支持跑步与骑行两种场景的差异化功能,包括实时轨迹记录、多维度路径分析(如配速、坡度、能耗)、数据可视化(地图标注、曲线图、3D回放)、异常提醒及智能优化建议,并可通过蓝牙/Wi-Fi同步数据至手机APP,支持社交分享与专业软件导出。技术架构涵盖硬件层、设备端与手机端软件层以及云端数据存储,强调低功耗设计与用户体验优化。经过实测验证,系统在定位精度、续航能力和场景识别准确率方面均达到预期指标,具备良好的实用性和扩展性。; 适合人群:具备定嵌入式开发或移动应用开发经验,熟悉物联网、传感器融合与数据可视化的技术人员,尤其是从事智能穿戴设备、运动健康类产品研发的工程师和产品经理;也适合高校相关专业学生作为项目实践参考。; 使用场景及目标:① 开发高精度运动轨迹记录功能,解决GPS漂移与断点问题;② 实现跑步与骑行场景下的差异化数据分析与个性化反馈;③ 构建完整的“终端采集-手机展示-云端存储”系统闭环,支持社交互动与商业拓展;④ 掌握低功耗优化、多源数据融合、动态功耗调节等关键技术在穿戴设备中的落地应用。; 阅读建议:此资源以真实项目为导向,不仅提供详细的技术实现路径,还包含硬件选型、测试验证与商业扩展思路,建议读者结合自身开发环境,逐步实现各模块功能,重点关注定位优化算法、功耗控制策略与跨平台数据同步机制的设计与调优。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值