`
grandboy
  • 浏览: 124842 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Building a Drag-and-Drop Shopping Cart with AJAX

    博客分类:
  • AJAX
阅读更多
The rise of AJAX over the past several months has taken over the development world and breathed new life into the Web. Although these techniques have been possible for many years now, the maturity of Web standards like XHTML and CSS now make it a viable alternative that will be viewable by all but the oldest browsers.

It's also been possible to accomplish many of the same things using Flex or Flash, but the development cycle with those applications is typically more involved and the overhead often not justified.

We're going to harness the power of the Scipt.aculo.us JavaScript library to provide our interaction. As their Web site states, this library "provides you with easy-to-use, compatible and, ultimately, totally cool JavaScript libraries to make your web sites and web applications fly, Web 2.0 style." We're also going to utilize the <CF_SRS> library to handle the actual AJAX data piping to our application. Both of these libraries are free for all to use, and they're easier to integrate than you would think.

For this article, we'll create an interactive shopping experience allowing us to add items to our shopping basket by dragging and dropping them onto an icon of a shopping cart. We'll add AJAX functionality, allowing us to update our shopping cart without redrawing the entire screen. To save the trouble of setting up a product database, we'll use Amazon Web Services to search for DVDs and use those to shop from.

Start with a blank index.cfm in your root directory. You'll need to visit http://script.aculo.us/downloads to download the latest distribution (they're nearing a final release for version 1.5 as of this writing). Copy the "lib" and "src" directories into your empty directory. You'll need all of the .js files so just copy over the entire directory in each case. Next, type the following lines into the <head></head> section of your page:

<script src="./lib/prototype.js" type="text/javascript"></script>
<script src="./src/scriptaculous.js" type="text/javascript"></script> 


We'll need a search box to submit our query to Amazon:

<form action="index.cfm" method="post">
Search: <input type="text" name="keywords" size="20" />
<input type="submit" name="search" value="Go" /> 
</form> 


The page will look for a form.search variable and run an Amazon search when it is defined. Each item returned will be placed in its own styled div that will be able to be picked up and dragged.

The Scriptaculous library makes it easy to create "draggables" (the only required argument is the ID of the object that you want draggable). Listing 1 (see attached) contains the code to search Amazon and return the results as draggable divs.

At this point, all of the items returned from the search will be in their own box and should be draggable around the screen. When we created each draggable, we set "revert=true", which will snap each object back to its original location if not placed directly on a drop zone.

Next, we'll add a graphic of a shopping cart to our page, which will become a drop target on which to drag items. The Scriptaculous library also makes it easy to create these "droppables". The syntax is simply:

Droppables.add('id_of_element',[options]); 


The code below creates a droppable zone of id "cart1" and also runs a function onDrop() that pops up an alert box letting the user know an item has being added. We then hide the element from view, which allows the other divs to slide over and adjust accordingly.

<img src="shopcart.jpg" id="cart1" style="float:left;">
<script language="javascript" type="text/javascript">
Droppables.add('cart1', { onDrop:function(element) { 
alert('Added UPC ' + element.id + ' to your shopping cart.');
Element.hide( element.id);}})
</script> 


The items should now be disappearing when dropped onto the shopping cart, but there's nothing going on behind the scenes yet. Now it's time to add some AJAX to process our shopping cart.

Although there are several AJAX libraries to choose from, we're going to use the ColdFusion Simple Remote Scripting <CF_SRS> library made available free of charge by Matthew Walker of ESWsoftware in New Zealand. <CF_SRS> uses an IFRAME for communication and encapsulates all of the dirty work for you. This library was chosen for its ability to handle HTML tables well and for its ability to interact directly with the browser's Document Object Model (DOM) to output our shopping cart rows.

We'll start with an empty cart by including the following code:

<fieldset style="width:400px;">
<legend>Your shopping cart</legend>
<table border="0" cellspacing="0" cellpadding="5" id="tableCart"> 
<thead></thead><tbody></tbody></table>
<button onclick="emptyCartButton_onClick()" id="emptyCartButton">
Clear Shopping Cart</button>
</fieldset> 


(Don't worry about the fact that our table body (<tbody></tbody>) is empty right now - we'll be populating it in just a second through AJAX.)

Next, you'll need to download the <CF_SRS> package from www.eswsoftware.com/products/download/ . Copy the srs.cfm file into your Webroot (or you can add it to your CustomTags directory if you plan to do more AJAXing). You'll also need to create a subdirectory to hold the gateway pages that handle our AJAX data passing. Name the directory "SRS" and copy the Application.cfm and OnRequestEnd.cfm files into there from the "serverpages" directory in the zip file. You can use either regular CFM files or CFCs for these gateway pages (the download provides examples of each). The main thing to remember is that these pages should always return their results to " request.response".

Simply adding a <cf_srs> call to your page will handle the creation of the hidden IFRAME for you. Another great feature of the CF_SRS library is the ability to view an inline debugging window right inside the page you are working on. This allows you to see all of the data being passed back and forth through the gateway. You can enable this debugging by calling the tag as <cf_srs trace>. This line can be placed anywhere but we'll add it at the very end of the file.

Next, we'll need to create some JavaScript functions to handle the AJAX interactions. Add an onLoad function to your body tag as such: <body onload="body_onLoad()">. This will execute body_onLoad() when the page loads and we'll use this function to set up our gateway. The function should read as follows:

function body_onLoad() {
// create an SRS gateway to the cart.cfm page
objGateway = new gateway("srs/cart.cfm?");
// update cart in case of return visit
// code for this function is below 
updateCart();
} 

Once you have created your gateway, you can invoke the methods below to send requests to the server:

objGateway.setListener( str ): Use this method to specify the name of the function in your Web page that will handle the server's response. str is a string representing the function's name. The listener defaults to "alert", which will pop up a JavaScript alert() box containing the server's response. Note that while ColdFusion is a case-insensitive language, JavaScript is case-sensitive. If you return a structure to your listener function, all the structure keys will be rendered in JavaScript as lowercase.
objGateway.setArguments( obj ): Set the arguments and values to pass to the server. obj is an object literal, which is basically just a set of one or more attribute/value pairs wrapped in curly braces. Here's an example: { name:'Joe', age:30, country:'US' }. You can see that string values need to be wrapped in quotation marks, and colons (:) are used in place of equals signs (=).
objGateway.resetArguments(): Remove all the arguments previously set.
objGateway.request(): Send the request to the server.
Note that you can chain these methods together. For example, it is perfectly acceptable to write:

objGateway.resetArguments().setArguments( { state:'NY' } ).request()

Using what we know now, let's take another look at our updateCart() function that we're calling onLoad.

function updateCart() { objGateway.setListener('cartPacket_onReceive').setArguments(
{action:'getCart'} ).request(); } 


The function chains together several commands. It sets the listener to "cartPacket_onReceive". That means that we'll execute this JavaScript function whenever data is returned from our gateway. This function handles the generation of our table body that contains our cart rows (see Listing 2).

In our updateCart() function, we're also passing in an argument: action=getCart. This is going to be passed through to our cart.cfm gateway page. The full text of the gateway page is displayed in Listing 3.

We're passing in the action variable with a value of "getCart". This gets passed to our cart.cfm gateway page and causes the user's session cart to be returned as a query object. Whenever we need to update our cart to add or delete rows, we'll set our listener to 'cartPacket_onReceive' and then redraw the table body.

When we created our shopping cart on screen, we added the following button to clear our cart:

<button onclick="emptyCartButton_onClick()" id="emptyCartButton">
Clear Shopping Cart</button> 


We'll add two JavaScript functions to go along with that button. The first will confirm the delete and the second will issue a call to remove the items and redraw the cart:

function emptyCartButton_onClick() {
   if ( confirm('Are you sure you want to empty your cart?') ) clearCart();
}

function clearCart() {
   objGateway.setListener('cartPacket_onReceive').setArguments( {action:'clearCart'} 
).request();
} 


Finally one more JavaScript function to be called when adding items to our cart:

function addToCart(upc) {
   objGateway.setListener('cartPacket_onReceive').setArguments( { action:'addToCart',upc:upc }
).request();
} 


Now that we have our addToCart() function coded, add the line "addToCart(element.id);" right before the Element.hide call in the shopping cart droppable. This will execute our addToCart() function and redraw the shopping cart when an item is dropped onto it.

And that's all there is to it! With just 150 lines of code, we were able to create an interactive, drag-and-drop shopping experience that many did not think was possible using just the browser.

分享到:
评论

相关推荐

    前端项目-angular-drag-and-drop-lists.zip

    前端项目-angular-drag-and-drop-lists,Angular directives for sorting nested lists using the HTML5 Drag and Drop API

    Drag-and-Drop:拖放,克隆,调整大小,删除和旋转

    快速开始首先,请克隆该项目并在终端中运行以下命令: $ git clone https://github.com/Big-Silver/Drag-and-Drop.git drag_drop$ cd drag_drop $ Run index.html in browser.In drag_drop.js$(document).ready...

    基于HTML5 拖拽接口(Drag and drag-and-drop interfaces based on HTML5

    HTML5是现代网页开发的重要标准,它引入了许多新特性,其中拖放(Drag and Drop)功能就是一项增强用户交互体验的重要接口。拖放接口允许用户通过鼠标或触控设备将元素从一个位置拖动到另一个位置,使得网页的互动性...

    angular-drag-and-drop:简单的Angular拖放库

    安装npm install angular-drag-and-drop-lib 用法为了访问库指令和组件,您必须从项目中导入AngularDragAndDropLibModule 。 import { AngularDragAndDropLibModule } from 'angular-drag-and-drop-lib';...@...

    drag-drop-folder-tree(功能强大的动态树)

    "drag-drop-folder-tree" 是一个专为实现这种功能而设计的组件,它不仅具备基本的树形展示,还提供了额外的交互功能,如节点的拖放操作和右键点击菜单。 动态树的核心特点在于其动态性,这意味着树中的节点可以根据...

    drag-and-drop实现浏览器的图片预览

    在IT行业中,拖放(Drag-and-Drop)功能是一种常见的用户交互方式,它允许用户通过鼠标操作将元素从一处移动到另一处。在本话题中,我们关注的是如何实现浏览器中的图片预览功能,特别是在拖放操作时。这个功能常见...

    Angular-ng-drag-drop.zip

    Angular-ng-drag-drop.zip,角度拖放-基于HTML5,无外部依赖关系。角度拖放,Angularjs于2016年发布,是Angularjs的重写版。它专注于良好的移动开发、模块化和改进的依赖注入。angular的设计目的是全面解决开发人员的...

    react-list-drag-and-drop:轻巧的Rea​​ct组件通过拖放来对列表元素进行重新排序

    安装 npm install --save react-list-drag-and-drop用法您必须具有要在列表中呈现的项目Array 。 不用在内部渲染它,而是使用渲染道具在组件内部渲染它。 import RLDD from 'react-list-drag-and-drop/lib/RLDD' ; ...

    Beautiful-and-Accessible-Drag-and-Drop-with-react-beautiful-dnd-notes

    # Beautiful-and-Accessible-Drag-and-Drop-with-react-beautiful-dnd-notes 讲师 描述 拖放 (dnd) 体验通常用于对内容列表进行垂直和水平排序。 react-beautiful-dnd 是这些用例的绝佳工具。 它利用渲染道具模式...

    cytoscape.js-compound-drag-and:用于添加和删除子项的复合节点拖放UI

    cytoscape化合物拖放描述用于添加和删除子项的复合节点拖放UI( )依存关系Cytoscape.js ^ 3.4.0使用说明下载库: 通过npm: npm install cytoscape-compound-drag-and-drop , 通过凉亭: bower install cytoscape-...

    v-drag-drop:Vue.js的简约拖放指令

    注意:v-drag-drop的2.x及更高版本仅与Vue 3兼容。 如果使用Vue 2,请安装1.x版。 旨在封装本机拖放API的某些特性,并使其更易于与Vue.js一起使用。 还添加了一些方便的功能,例如名称空间。 目录 安装 安装v-drag-...

    drag-and-drop

    Git bash,运行npm cache clean && npm install 从 Git bash 运行bower cache clean && bower install 从 Git bash 运行git checkout -b your-branch-name 在命令行窗口中,导航到drag-and-drop目录运行grunt test-...

    drag-drop-folder-tree.rar_Tree 菜单_drag drop java_drag-drop-fold

    本文将深入探讨“drag-drop-folder-tree.rar”这个压缩包所包含的资源,它提供了一个强大的动态树视图,支持节点的拖放操作,并且允许用户通过右键点击进行交互。 首先,"Tree 菜单"指的是在图形用户界面中用于展示...

    TS-Drag-and-Drop

    【标题】:“TS-Drag-and-Drop”是一个基于TypeScript实现的拖放功能库 【描述】:在现代Web开发中,用户交互性是至关重要的,拖放(Drag and Drop)功能可以极大地提升用户体验。"TS-Drag-and-Drop"项目就是针对这一...

    cypress-drag-drop:用于拖放支持的 cypress 子命令

    npm install --save-dev @4tw/cypress-drag-drop 或纱线 yarn add --dev @4tw/cypress-drag-drop 在加载 Cypress 之前(通常在您的commands.js )放置以下行: require ( '@4tw/cypress-drag-drop' ) 或者,...

    The Drag and Drop Component Suite for Delphi XE10

    对于Delphi开发者来说,"The Drag and Drop Component Suite for Delphi XE10"是一款非常实用的工具,它极大地简化了在Delphi XE10环境下实现拖放功能的复杂度。 该组件套件是基于先前版本XE7的修改版,经过优化后...

    drag-and-drop-alt

    与原来的drag-and-drop不同,这个应用程序是用纯 JS 编写的,没有外部依赖。要使用该应用程序: 克隆 repo ( ) 导航到drag-and-drop-alt/client/目录用 Chrome 打开index.html继续开发(在 Windows 中):依赖关系...

    js动态树合集(dtree,dhtmlxtree,drag-drop-tree)

    在给定的压缩包文件中,包含了几种不同的库,如dtree、dhtmlxtree(1.5普通版及1.3专业版)以及drag-drop-tree,这些都是用于实现动态树功能的JavaScript库。接下来,我们将深入探讨这些库及其相关的知识点。 1. ...

    Drag-a-Drop-UI.rar_drop_labview ui

    "Drag-a-Drop-UI.rar_drop_labview ui" 提供的功能允许开发人员在程序运行时动态调整前面板控件的位置,极大地提高了设计的灵活性和用户体验。 首先,我们要理解“拖放”(Drag & Drop)技术在LabVIEW中的应用。...

    ngx-drag-and-drop-lists:列表的角度拖放组件

    ngx拖放列表 ... 指令也可以嵌套以将拖放拖放到所见即所得编辑器,树或正在构建的任何奇特结构中。 归功于原始创作者 该库的灵感来自以AngularJS编写的库。 拖动元素输入 dndDraggable必需属性。 表示此元素是...

Global site tag (gtag.js) - Google Analytics