Sharepoint学习笔记—ECMAScript对象模型系列-- 6、使用ECMA操作列表项对象(list item)...

  前面我们使用ECMAScript对象模型操作website对象,list对象,这里我们进一步看看如何使用模型来操作列表项List item对象。

  实践之前,首先需要在我们的Sharepoint网站上创建一个名为product的list,如下图:

 

  一、添加List Item--新增一个product(Add Product)

   < input  id ="btnNewProduct"  type ="button"  value ="Add Product"  onclick ='addProduct("AsusLapTop4",  "Asus AX44H4 Laptop2", "2011-12-16", "46", "Computer")'  />

 

< script  type ="text/javascript" >
    
// Add Item to List
     // The code snippet below shows that  you need to get the current SharePoint Context first. 
     // Then get the current web from the context. And then you need to get the list from the web. 
     // Then I have used ListItemCreationInformation object. There are two important properties of ListItemCreationInforamtion:
     // ListItemCreationInformation.folderUrl: this property defines in which location you want to add the item. 
     // The url should start with forward slash(/). For example for the web myweb and list product and for the folder ‘myfolder’ 
     // in the product list the url will be  ‘/myweb/Lists/product/myfolder’. 
     // ListItemCreationInformation.UnderlyingObjectType: this value identity the type of object to create. 
     // The possible values are File,Folder, Web and Invalide. The values can be found in ‘SP.FileSystemObjectType’. 
     // The addProduct method below takes few arguments that represents the product list’s fields.

    
function  addProduct(productName, productDesc, productLaunchDate, productAvailQty, productType) {
        
try  {
            
var  context  =   new  SP.ClientContext.get_current();
            
var  web  =  context.get_web();
            
var  list  =  web.get_lists().getByTitle( ' product ' );
            
var  listItemCreationInfo  =   new  SP.ListItemCreationInformation();
            
var  newItem  =  list.addItem(listItemCreationInfo);
            newItem.set_item(
' Title ' , productName); newItem.set_item( ' ProductName ' , productName); newItem.set_item( ' ProductDescription ' , productDesc);
            newItem.set_item(
' LaunchDate ' , productLaunchDate);
            newItem.set_item(
' AvailableQuantity ' , productAvailQty);
            newItem.set_item(
' ProductType ' , productType); newItem.update();
            context.executeQueryAsync(Function.createDelegate(
this this .addProductsuccess),
                                      Function.createDelegate(
this this .addProductfailed));
        } 
catch  (e) { alert( ' error: '   +  e.Message); }
    }

    
// If you look a bit closer in the above code snippet you can find that ClientContext.executeQueryAsync
     //  takes two function delegates. The first one will be invoked when the ECMAScript get executed successfully. 
     // The second one will be invoked otherwise. The two methods are defined below:

    
function  addProductsuccess() { alert( ' add Product success ' ); }
    
function  addProductfailed(sender, args) {
        alert(
' failed. Message: '   +  args.get_message());
    }

</ script >

 

 

  二、删除List Item--删除一个product(Delete Product) 

    < input  id ="btnDeleteProduct"  type ="button"  value ="Delete Product"  onclick ='deleteProduct(1)'  />

 

< script  type ="text/javascript" >
    
// Delete Item
     // To delete a product by product id the following code snippet can be used:
     // To delete an object in Client Object Model you need to invoke the deleteObject method of that object.

    
function  deleteProduct(productId) {
        
var  context  =   new  SP.ClientContext.get_current();
        
var  web  =  context.get_web();
        
var  list  =  web.get_lists().getByTitle( ' product ' );
        
var  itemToDelete  =  list.getItemById(productId);
        itemToDelete.deleteObject();
        context.executeQueryAsync(Function.createDelegate(
this this .deleteProductsuccess),
                                  Function.createDelegate(
this this .deleteProductfailed));
    }


    
function  deleteProductsuccess() { alert( ' delete Product success ' ); }
    
function  deleteProductfailed(sender, args) {
        alert(
' failed. Message: '   +  args.get_message());
    }


</ script >

 

  三、检索List Item--根据ProductID来获取一个product(Get Item By ProductID)

    < input  id ="btnGetItemByID"  type ="button"  value ="Get Item By ProductID"  onclick ='getProductById(2)'  />

 

< script  type ="text/javascript" >
    
//  Get Item by ID
     // To get an item using ECMAScript, you need to share a common variable between the method that 
     // execute the ECMAScript (getProductById method in the following code snippet) and
     //  callback method (productReceived, failed in the snippet below). 
     // Only for this reason I have defined a variable product in the first line of the code snippet below. 
     var  product;
    
function  getProductById(productId) {
        
try  {
            
var  context  =   new  SP.ClientContext.get_current();
            
var  web  =  context.get_web();
            
var  list  =  web.get_lists().getByTitle( ' product ' );
            
this .product  =  list.getItemById(productId);
            context.load(product, 
' ProductName ' ' ProductDescription ' ' ProductType ' ' LaunchDate ' ' AvailableQuantity ' );
            context.executeQueryAsync(Function.createDelegate(
this this .getProductByIdproductReceived),
                                      Function.createDelegate(
this this .getProductByIdfailed));
        }
        
catch  (e) {
            alert(e);
        }
    }
    
function  getProductByIdproductReceived() {
        
// alert('got product');
        gotProduct( this .product);
    }

    
function  getProductByIdfailed(sender, args) {
        alert(
' failed. Message: '   +  args.get_message());
    }

    
function  gotProduct(item) {
        alert(
" ProductName:  "   +  item.get_item( " ProductName " +   " \r\ProductDescription:  "   +  item.get_item( " ProductDescription " ));
    } 

</ script >

 

  四、查找list Item--在product列表中查找product(search Item By ProductTitle)

< input  id ="btnSearchItem"  type ="button"  value ="Search Item By ProductTitle"  onclick ='getProducts("AsusLapTop4")'  />

 

< script  type ="text/javascript" >
    
// Search Items from a List
     // In the code snippet below Caml Query is used for searching a product by title. 
     // I have used Caml Query to search product by title. Notice here that the load takes a second parameter (wrapped with ‘include’)
     //  specifying all properties to load for items.

    
debugger ;
    
var  productcollection;
    
function  getProducts(title) {
        
try  {
            
var  context  =   new  SP.ClientContext.get_current();
            
var  web  =  context.get_web();
            
var  list  =  web.get_lists().getByTitle( ' product ' );

            
var  query  =   ' <View Scope=\'RecursiveAll\'> '   +   ' <Query> '   +   ' <Where> '   +
                            
' <Contains> '   +   ' <FieldRef Name=\'ProductName\'/> '   +
                                
' <Value Type=\'Text\'> '   +  title  +   ' </Value> '   +
                            
' </Contains> '   +
                            
' </Where> '   +   ' </Query> '   +
                               
' </View> ' ;


            
var  query2  =   ' <View Scope=\'RecursiveAll\'> '   +   ' <Query> '   +   ' <Where> '   +
                            
' <Contains> '   +   ' <FieldRef Name=\'ProductName\'/> '   +
                                
' <Value Type=\'Text\'> '   +  title  +   ' </Value> '   +
                            
' </Contains> '   +
                            
' </Where> '   +   ' </Query> '   +
                             
' <ViewFields><FieldRef Name="ProductName"/><FieldRef Name="ProductDescription"/></ViewFields> ' ;

            
var  query3  =   ' <View Scope=\'RecursiveAll\'> '   +   ' <Query> '   +   ' <Where> '   +
                            
' <Contains> '   +   ' <FieldRef Name=\'ProductName\'/> '   +
                                
' <Value Type=\'Text\'> '   +  title  +   ' </Value> '   +
                            
' </Contains> '   +
                            
' </Where> '   +   ' </Query> '   +
                               
' </View> ' ;

            
var  camlQuery  =   new  SP.CamlQuery();
            camlQuery.set_viewXml(query3);

            
this .productcollection  =  list.getItems(camlQuery);
            context.load(
this .productcollection,  ' Include(ProductName, ProductDescription, ProductType, LaunchDate, AvailableQuantity) ' );
            context.executeQueryAsync(Function.createDelegate(
this this .getProductsproductsReceived),
            Function.createDelegate(
this this .getProductsfailed));
        } 
catch  (e) { alert(e); }
    }

    
function  getProductsproductsReceived() {
        
//  alert('got products');
         var  listEnumerator  =   this .productcollection.getEnumerator();
        prcessProducts(
this .productcollection);
        
//  prcessProducts(listEnumerator);
         // onQuerySucceeded(this.productcollection);

    }

    
function  prcessProducts(items) {
        
var  count  =   0 ;
        
var  TextFiled  =   '' ;
        
var  ListEnumerator  =  items.getEnumerator();
        
while  (ListEnumerator.moveNext()) {
            count 
=  count  +   1 ;
            
var  currentItem  =  ListEnumerator.get_current();
            
//  do something with this here. Coupled with a platform like jQuery, you could do all kinds of great things 
            TextFiled  +=  currentItem.get_item( ' ProductName ' ).toString();

        }
        alert(TextFiled);
        alert(count);

    }

    
function  getProductsfailed(sender, args) {
        alert(
' failed. Message: '   +  args.get_message());
    }


    
function  onQuerySucceeded(collList) {

        
var  listInfo  =   '' ;
        
for  ( var  i  =   0 ; i  <   this .productcollection.length; i ++ ) {
            
var  oList  =   this .productcollection[i];
            
// listInfo += 'Title: ' + oList.get_title() + ' ID: ' + oList.get_id().toString();
            listInfo  +=   " ProductName:  "   +  oList.get_item( " ProductName " +   " \r\ProductDescription:  "   +  oList.get_item( " ProductDescription " );
        }
        listInfo 
+=   this .product.length;
        alert(listInfo.toString());


        
//         var listInfo = '';
         //         var listEnumerator = collList.getEnumerator();
         //         for (var i = 0; i < this.listEnumerator.length; i++) {
         //             var oList = this.listEnumerator[i];
         //             listInfo += 'Title: ' + oList.get_title() + ' Created: ' + oList.get_created().toString() + '\n';
         //         }
         //         while (listEnumerator.moveNext()) {
         //             var oList = listEnumerator.get_current();
         //             //listInfo += 'Title: ' + oList.get_title() + ' Created: ' + oList.get_created().toString() + '\n';
         //             listInfo += "ProductName: " + oList.get_item("ProductName") + "\r\ProductDescription: " + oList.get_item("ProductDescription");
         //         }
         //         alert(listInfo);
    }

</ script >

 

  五、更新List Item--更新product(Update Items for a List)

   < input  id ="btnUpdateItem"  type ="button"  value ="Update a Product"  onclick ='updateProduct(3,  "AsusLapTopNew3", "Asus Lap Top New Desc3", "2011-12-18", "100", "Computer") '  />

 

< script  type ="text/javascript" >
    
// Update a list item
     // The code snippet below shows how to update a product item. 
     // The list item’s set_item(propertyname, propertyvalue) method is used to update the field values.

    
function  updateProduct(productid, productName, productDesc, productLaunchDate, productAvailQty, productType) {
        
var  context  =   new  SP.ClientContext.get_current();
        
var  web  =  context.get_web();
        
var  list  =  web.get_lists().getByTitle( ' product ' );
        
var  product  =  list.getItemById(productid);
        product.set_item(
' ProductName ' , productName);
        product.set_item(
' ProductDescription ' , productDesc);
        product.set_item(
' ProductType ' , productType);
        product.set_item(
' LaunchDate ' , productLaunchDate);
        product.set_item(
' AvailableQuantity ' , productAvailQty);
        product.update();
        context.executeQueryAsync(Function.createDelegate(
this this .updateProductsuccess), Function.createDelegate( this this .updateProductfailed));

    }

    
function  updateProductsuccess() {
        alert(
' Update products ' );
    }
    
function  updateProductfailed(sender, args) {
        alert(
' failed. Message: '   +  args.get_message());
    }

</ script >

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值