`
seebysee
  • 浏览: 10839 次
  • 性别: Icon_minigender_1
  • 来自: 沈阳
社区版块
存档分类
最新评论

Simplify Ajax development with jQuery 使用Jquery简化Ajax开发(II)

阅读更多
简单实现Ajax
Ajax couldn't be any easier than it is with jQuery. jQuery has a handful of functions that make the easy stuff really easy and the complex stuff as simple as possible.
A common use of Ajax is to load a chunk of HTML into an area of the page. To do that, simply select the element you need and use the load() function. Here's an example that updates some statistics:
$('#stats').load('stats.html');
不会再有比jQuery更简单的方法实现Ajax了。jQuery有很多功能可以使复杂的变为简单,简单的更加简单。一种经常使用的Ajax实现是将一大堆HTML查到页面的某个区域中去。可以使用load()函数轻松的实现。这个例子更新了一些统计数据。
 
Often, you simply need to pass some parameters to a page on the server. As you'd expect, this is incredibly simple in jQuery, too. You can use choose between $.post() and $.get(), depending on which method you need. You can pass an optional data object and callback function if you need them. Listing 4 shows a simple example that sends data and uses a callback.
通常,你仅仅是需要向服务器传送一些参数。和你预期的一样,在jQuery中会超乎想象的简单。你可以选择$.post()或是$.get()函数,这取决于你希望使用那种提交方式。如果需要的话,还可以传送一个可选数据和回调函数。Listing4展示了一个发送数据并使用回调函数的简单例子。
        
$.post('save.cgi', {
    text: 'my string',
    number: 23
}, function() {
    alert('Your data has been saved.');
});
 
If you really want to do some complex Ajax scripting, you need the $.ajax() function. You can specify xml, html, script, or json, and jQuery automatically prepares the result for your callback function so that you can use it right away. You can also specify beforeSend, error, success, or complete callbacks to give the user more feedback about the Ajax experience. In addition, other parameters are available with which you can set the timeout of an Ajax request or the "Last Modified" state of a page. Listing 5 shows an example that retrieves an XML document using some of the parameters that I mentioned.
如果你真的需要制作一些复杂的Ajax脚本,你就需要用到$.ajax()方法。你可以指定xml,html,script 或者是json,jQuery自动为你准备了一些回调函数,以便你可以马上使用。你同样也可以指定beforesenderrorsuccess或者是complete来为用户提供更多的Ajax体验。而且,你可以设置请求超时或者是“最近更新”的页面状态的参数。Listing5提供了一个使用前面提供的参数取得一个XML文档的例子。
        
$.ajax({
    url: 'document.xml',
    type: 'GET',
    dataType: 'xml',
    timeout: 1000,
    error: function(){
        alert('Error loading XML document');
    },
    success: function(xml){
        // do something with xml
    }
});
 
When you get the XML back in the success callback, you can use jQuery to look through the XML the same way you do with HTML. This makes it easy to work with an XML document and integrate the contents and data into your Web site. Listing 6 shows an expansion on the success function that adds a list item to the Web page for each <item> element in the XML.
当你使用success回调函数取得XML,你可以使用jQuery像遍历HTML一样来遍历XML文档。这使得操作XML文档并将内容和数据整合到站点中变得相当简单。Listing6展示了一种扩展success方法来向XML页面中的每一个<item>元素添加一个list元素。
        
success: function(xml){
    $(xml).find('item').each(function(){
        var item_text = $(this).text();
 
        $('<li></li>')
            .html(item_text)
            .appendTo('ol');
    });
}
 
 
 
HTML的动画效果
You can use jQuery to take care of basic animations and effects. At the heart of the animation code is the animate() function, which changes any numeric CSS style value over time. For example, you can animate height, width, opacity, or position. You can also specify the speed of the animation, either in milliseconds or in one of the predefined speeds: slow, normal, or fast.
Here's an example that animates the height and width of an element at the same time. Notice that there is no start value -- only the end value. The start values are taken from the current size of the element. I've also attached a callback function.
你可以使用jQuery来创建简单的动画效果。动画的核心是animate()方法,它通过改变CSS的数字实现动画效果。例如,你可以创建关于高度,宽度,透明度或是位置的动画。当然你也可以指定动画的播放速度。
下面是一个同时改变元素对象高度和宽度的动画。注意,这里没有开始值,只有结束值,开始值取决于元素当前的大小。我还加入了一个回调函数。
$('#grow').animate({ height: 500, width: 500 }, "slow", function(){
    alert('The element is done growing!');
});
 
jQuery makes the more common animations easier with built-in functions. You can use show() and hide() elements, either instantly or at a specified speed. You can also make elements appear and disappear by using fadeIn() and fadeOut() or slideDown() and slideUp(), depending on what kind of effect you're looking for. Here's a simple example that slides down a navigation:
$('#nav').slideDown('slow');
jQuery在内建函数的帮助之下,使得实现更多的常规动画变得更加简单。你可以使用show()函数或是hide函数使得元素对象立刻或者依照你指定的速度作变化。你同样可以利用fadein(),fadeout(),slidedown(),sldedown()函数使元素出现或者消失,这主要取决于你所希望出现的效果。下面是一个简单的导航栏的滑动实例。
 
jQuery is, perhaps, best at simplifying DOM scripting and event handling. Traversing and manipulating the DOM is easy, and attaching, removing, and calling events is completely natural and much less error prone than doing it by hand.
In essence, jQuery makes it easier to do things that are common with DOM scripting. You can create elements and use the append() function to link them to other elements, use clone() to duplicate elements, set the contents with html(), delete the contents with the empty() function, delete the elements altogether with the remove() function, and even use the wrap() function to wrap the elements with another element.
Several functions are available for changing the contents of the jQuery object itself by traversing the DOM. You can get all the siblings(), parents(), or children() of an element. You can also select the next() or prev() sibling elements. Perhaps most powerful is the find() function, which allows you to use a jQuery selector to search through the descendants of elements in your jQuery object.
These functions become more powerful when used with the end() function. This function is like an undo function, going back to the jQuery object you had before you called find() or parents() or one of the other traversing functions.
When used together with method chaining, these functions allow complex operations to look simple. Listing 7 shows an example in which you find a login form and manipulate several elements around it.
jQuery或许是简化DOM,时间句柄处理的最佳简化方案了。你可以通过append()函数建立一个元素与其他元素的关系,使用clone()函数复制元素,使用html()函数设置它的内容,使用empty()函数清空内容,使用remove()函数删除绑定在一起的所有元素。甚至是使用wrap函数来将一个元素绑定到另一个元素上去。
一些函数通过遍历DOM来改变jQuery对象的内容。你可以利用siblings(),parents()或者是children()函数来获得相应的元素。你当然也可以通过next()或者是prev()滑动(查看)元素。或者是用功能更加强大的find()函数,它可以让你使用jQuery选择器在你的jQuery中寻找所有的子元素。
这些函数在于end()函数一起使用的时候会变得更加强大。End()函数就像一个undo(撤销操作)函数,使你可以得到之前用find(), parents()或者是其他遍历函数得到的元素的前一个元素。
当同时使用函数链的时候,这些函数将会使得复杂的操作变得更加简单。Listing7举了个例子,其中你可以看到一个登陆表单并且操作它周围的一些元素。
        
$('form#login')
    // hide all the labels inside the form with the 'optional' class
    .find('label.optional').hide().end()
 
    // add a red border to any password fields in the form
    .find('input:password').css('border', '1px solid red').end()
 
    // add a submit handler to the form
    .submit(function(){
        return confirm('Are you sure you want to submit?');
    });
 
Believe it or not, this example is just a single, chained, line of code spread out with whitespace. First, I selected the login form. Then, I found the optional labels inside it, hid them, and called end() to go back to the form. I found the password field, made the border red, and again called end() to go back to the form. Finally, I added a submit event handler to the form. What's especially interesting about this (besides its obvious brevity) is that jQuery completely optimizes all the query operations, making sure that you don't have to find an element twice when everything is nicely chained together.
Handling common events is as simple as calling a function like click(), submit(), or mouseover() and passing it an event handler function. Additionally, you have the option of assigning a custom event handler using bind('eventname', function(){}). You can remove certain events using unbind('eventname') or all events with unbind(). For a complete list of ways to use these and other functions, check out the jQuery application program interface (API) documentation in the Resources.
不论你相信不相信,这个例子还是一个单行的,像条链子一样,不纯在空格的一段代码。首先,我选择了登陆表单。然后,我找到了里面的选择标签,隐藏掉它,最后调用end()函数回到表单元素。又发现了密码输入框,使它的边框变红,然后再调用end()函数回到f表单元素。最后,我为form元素添加了一个提交事件的句柄。jQuery完全优化了所有的查询操作,以保证你不需要在所有东西都链接在一起之后还要来查找这个元素第二次。
处理常规的时间很简单,调用像click(),submit()或者是mouseover()函数然后传送(调用)一个事件的句柄函数。除此之外,你还可以选择自己建立时间句柄,通过使用bind(‘eventname’,function(){})。你也可以通过使用unbind(‘eventname’)解除特定的时间绑定,或者使用unbind()解除所有事件。如果需要完整的列表来使用其他函数,请查看jQueryAPI
 
 
释放jQuery选择器的潜力!
Often, you select elements by ID, such as #myid, or by class name, such as div.myclass. However, jQuery has a rather complex and complete selector syntax that allows you to select nearly any combination of elements in a single selector.
jQuery's selector syntax is based heavily on CSS3 and XPath. The more you know about CSS3 and XPath syntax, the better you'll be at using jQuery. For a complete list of jQuery selectors, including CSS and XPath, check out the links in Resources.
CSS3 contains some syntax that not every browser supports, so you don't see it often. However, you can still use CSS3 in jQuery to select elements, because jQuery has its own, custom selector engine. For example, to add a dash inside every empty column of a table, use the :empty pseudo-selector:
通常情况下,你会通过使用divMyclass这样的类名或者id来选择一个元素。然而,jQuery拥有一个非常复杂和全面的选择变量,使得你可以选择几乎所有的单个元素,或是一组元素。
jQuery的选择器变量基于CSS3Xpath。你对CSS3Xpath的了解将会使得你更好的使用jQuery。如果需要jQuery选择器的完整列表,请点击Resource中的链接。
CSS3包含了许多现在浏览器还不支持的语法,所以你可能不会很熟悉它。然而,你仍然可以在jQuery中使用CSS3来选择元素,因为jQuery拥有它自己独特的选择器引擎。举个例子,在一个表格中所有空栏中加入破折号,可以使用empty伪选择器。
$('td:empty').html('-');
 
What about finding every element that doesn't have a certain class? CSS3 has a syntax for that, too, using the :not pseudo-selector. Here's how you can hide every input that doesn't have a class of required:
如何选择不包含特定节点的所有节点?CSS3有一个可以使用的语法:使用not伪选择器。下面的例子隐藏了所有不包含required类的文本输入框。
 
$('input:not(.required)').hide();
 
You can also join multiple selectors into one using commas, just as in CSS. Here's a simple example that hides every type of list on the page at the same time:
你也可以使用逗号来加入多重选择,就像使用CSS一样。这个例子同时隐藏当前页面中的各种列表。
$('ul, ol, dl').hide();
 
XPath is a powerful syntax for finding elements in a document. It's a bit different than CSS and lets you do a few things you can't do with CSS. To add a border to the parent element of every check box, you can use XPath's /.. syntax:
Xpath在文档中查找节点上功能强大。这和CSS有些不同,并且可以完成一些CSS无法完成的事情。为每一个多选框的父节点都加上边框,你可以像下面这样使用Xpath语句:
$("input:checkbox/..").css('border', '1px solid #777');
 
jQuery adds extra selectors that aren't available in CSS or XPath, as well. For example, to make a table more readable, you would typically attach a different class name to every odd or even row of the table -- otherwise known as striping the table. Doing this with jQuery is a cinch, thanks to the :odd pseudo-selector. This example changes the background of every odd row in tables with a striped class:
jQuery也支持一些在CSSXpath中都不支持的选择器。比如你想让一个表格更具可读性,你通常会每隔一行附加一个样式表。
$('table.striped > tr:odd').css('background', '#999999');
 
You can see how the power of jQuery selectors can simplify your code. Whatever selection of elements you want to affect, no matter how specific or obscure, you can probably find a way to define them using a single jQuery selector.
强大的Jquery选择器可以简化你的代码。不论你要选择的节点是多么的特定或是隐讳,你都会在jQuery选择器中找到一种方法。
 
使用插件扩展jQuery
Unlike with most software, writing plug-ins for jQuery isn't a huge ordeal with a complex API. In fact, jQuery plug-ins are so easy to write that you might want to write a few to make your code even simpler. Here's the most basic jQuery plug-in you can write:
与大多数软件不同,为jQuery开发插件并不会用到复杂的API函数。事实上,jQuery制作插件非常简单,而且可以使你的代码更加简单。这里给出了一些基本的jQuery插件。
$.fn.donothing = function(){
    return this;
};
 
Although simple, this plug-in does require a bit of explanation. First, to add a function to every jQuery object, you must assign it to $.fn. Next, this function must return this (the jQuery object) so that it doesn't break method chaining.
 
尽管简单,这个插件还是需要一些解释。首先,为每一个jQuery加入一个函数,你必须使用$.fn调用他,然后,这个函数必须返回this,自由这样,才不会破坏jQuery的函数链。
 
You can easily build on top of this simple example. To write a plug-in to change the background instead of using css('background'), you use this:
你可以轻松的使用这个例子。写一个插件,用来改变背景,而不使用css(“background”),you use this
$.fn.background = function(bg){
    return this.css('background', bg);
};
 
Notice that I could just return the value from css(), because it already returns the jQuery object. So, method chaining will still work fine.
I recommend that you use jQuery plug-ins anytime you find that you repeat yourself. For example, you might use a plug-in if you're using the each() function to do the same thing over and over.
Because jQuery plug-ins are so easy to write, hundreds of them are available for you to use. jQuery has plug-ins for tabs, rounded corners, slide shows, tool tips, date selectors, and probably anything else you can imagine. For a complete list of plug-ins, check out the Resources.
The most complex and most widely used plug-in is Interface, an animation plug-in that handles sorting, drag-and-drop functionality, complex effects, and other interesting and complex user interfaces (UIs). Interface is to jQuery what Scriptaculous is to Prototype.
Also popular and useful is the Form plug-in, which allows you to easily submit a form in the background using Ajax. This plug-in takes care of the common situation in which you need to hijack the submit event of a form, then find all the different input fields and use them to construct an Ajax call.
 
你可能注意到,我仅仅是从css()返回了一个值,因为它已经返回了一个jQuery对象。所以,函数链仍然会工作的很好。
我建议在发现重复的时候使用jQuery的插件。举个例子,当你在使用each()函数来一遍又一遍的作相同的事情,就应该使用到插件。因为jQuery的插件编写相当的简单,你可以使用数以百计的插件。jQuery有标签,圆角,滑动显示,工具提示,日期选择,或是其他你可以想得到的其他功能的插件。如果需要jQuery的全部插件列表,可以访问如下链接。
使用最广泛也是最复杂的插件是interface插件,这是一个动画插件,他可以处理排序,拖放功能,复杂的效果和其他一些复杂但有趣的用户界面。Interface对于jQuery就好像ScriptaculousPrototype一样重要。
同样受欢迎的插件还有From,它可以使你轻松的使用Ajax的处理表单。这个插件用来劫持表单对象的事件,然后使用不同的输入框建立Ajax调用。
 
I've only scratched the surface of what is possible with jQuery. jQuery is fun to use, because you always learn new tricks and features that seem so natural. jQuery simplifies your JavaScript and Ajax programming completely from the first moment you use it; every time you learn something new, your code gets a bit simpler.
After learning jQuery, I've had a lot more fun programming in the JavaScript language. All the boring stuff is taken care of, so I can focus on coding the juicy stuff. With jQuery, I can barely remember the last time I wrote a for loop. I even cringe at the thought of working with other JavaScript libraries. jQuery has honestly and truly changed the way I look at JavaScript programing forever.
我仅仅是学会了jQuery的表面上的东西。使用jQuery是一件快乐的事情,你会不停的发现学习到新的技巧和特性,而这一切是那么的自然。jQuery简化了你的JavascriptAjax编程从你使用它的那一刻起。你每学会一些新的东西,你的代码就回变得简单一些。
在学习了jQuery之后,我觉得使用Javascript语言编程更加有趣。使用jQuery,我几乎忘记了最后一次写for循环是在什么时候。我甚至不愿意在工作中使用其他JavaScript库。jQuery永远改变了我对Javascript编程方法
 
分享到:
评论

相关推荐

    JQuery In Action.PDF

    - **Utility Functions:** JQuery includes a set of utility functions that simplify common tasks such as manipulating CSS styles, adding classes, or applying animations. - **Example:** `.addClass(...

    easy-ajax:基于 jQuery 的 Ajax 调用封装,简化常用场景下的 Ajax 调用

    易阿贾克斯 Based jQuery to build easy ajax api, to simplify ajax request for:1. Dialog2. Form, and submitting3. HTTP asynchronous loading4. others先决条件 1. jQuery2. jQuery Dialog Model安装 1. Setup ...

    Unity使用Mesh Simplify 减面(网格简化)

    此插件用于简化网格 使用方法: 只需要添加组件"Mesh Simplify"组件到需要简化网格的对象上,点击Compute mesh即可, 如果操作报错的话,开启模型的Read/write Enabled就好了 操作简单,方便使用

    [JavaScript] JavaScript 从入门到精通 (英文版)

    Speed up and simplify app development with jQuery Quickly retrieve data from a server using AJAX requests Adapt your app for mobile devices with jQuery Mobile Build Windows 8 apps using HTML, CSS, and...

    《 jQuery实战.pdf》高清下载

    9. 简化脚本编写(Simplify Scripting):jQuery通过消除跨浏览器兼容问题,提供简洁的API,使得编写和维护JavaScript代码变得更加简单。 10. 社区支持(Community Support):由于其广泛的用户群和活跃的社区,...

    jquery Simplify your JavaScript

    Matthew Dawes Pacific Northwest National Laboratory Interlab 2007

    Java.EE.7.Development.with.NetBeans.8

    NetBeans has several features that greatly simplify Java EE development, but with many features and great flexibility, Java developers can become overwhelmed by the options available in NetBeans. ...

    MeshSimplify.rar

    总之,MeshSimplify.rar中的模型减面插件是Unity开发人员的理想工具,它提供了高效且易于使用的模型简化解决方案,帮助开发者在性能和视觉效果之间找到最佳平衡。通过深入理解和利用这个工具,开发者可以提升他们的...

    simplify-js, 高性能JavaScript多段线简化库.zip

    simplify-js, 高性能JavaScript多段线简化库 Simplify.js 是由 Vladimir Agafonkin简化的高性能JavaScript多线线简化库,从 Leaflet中提取。使用文档签出演示: http://mourner.github.io/simplify-js/端

    MeshSimplify:网格简化的实用程序

    MeshSimplify 是一个多边形网格简化程序。 它可用于创建具有任意数量面的输入网格的简化变体。 此外,该程序能够生成渐进式网格表示,作为简化过程的一部分,可用于 3d 对象的平滑多分辨率渲染。 使用MeshSimplify ...

    simplify-geometry:使用 Ramer-Douglas-Peucker 算法简化几何

    简化几何 使用简化几何。 如果您需要简化几何图形,例如减少多边形中的点数,这将对您有所帮助。 您可以在使用它。节点例子 var simplify = require ( 'simplify-geometry' ) ;var linestring = [ [ 0 , 0 ] , [ 2.5...

    turf-simplify:简化地理形状

    草皮简化 简化地理形状turf.simplify(feature, tolerance, highQuality) 接受LineString或Polygon并返回简化版本。 内部使用进行简化。参数范围类型描述feature 功能。&lt;LineString&gt; tolerance 数字简化公差...

    Professional.ASP.NET.2.0.AJAX

    This detailed guide to the Microsoft AJAX Library shows you how to bring together ASP.NET 2.0 with an object-oriented approach to JavaScript development using this new framework from Microsoft....

    Simplify-Testing-with-React-Testing-Library:Packt发布的使用React Testing Library简化测试

    使用React Testing库简化测试 这是Packt发布的“ 的代码库。 使用RTL创建可保持不变的测试 这本书是关于什么的? React Testing Library(RTL)是一个轻巧且易于使用的工具,用于测试组件的文档对象模型(DOM)...

    藏经阁-Simplify Machine Learning With Flink TableAPI.pdf

    Flink TableAPI 是 Apache Flink 的一部分,是一个高级别的分析 API,旨在简化机器学习的开发过程。Table API 提供了一个统一的接口来处理批处理和流处理数据,能够满足机器学习算法对 API 的核心需求。 Table API ...

    simplify-1.2.1.jar

    Simplify工具 反混淆 最新版本simplify.jar,参考https://github.com/CalebFenton/simplify 编译而成

    Mesh Simplify插件 v1.10.rar

    Mesh Simplify的核心功能在于模型减面,即通过算法将三维模型的几何信息进行简化,降低模型的多边形数量,从而减少计算量,提高运行效率。这个过程并不会显著影响模型的整体外观,保持了视觉上的逼真度。对于游戏...

Global site tag (gtag.js) - Google Analytics