现在的位置: 首页 > 综合 > 正文

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

2012年12月05日 ⁄ 综合 ⁄ 共 8291字 ⁄ 字号 评论关闭

  前面我们使用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(
thisthis.addProductsuccess),
                                      Function.createDelegate(
thisthis.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(
thisthis.deleteProductsuccess),
                                  Function.createDelegate(
thisthis.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(
thisthis.getProductByIdproductReceived),
                                      Function.createDelegate(
thisthis.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(
thisthis.getProductsproductsReceived),
            Function.createDelegate(
thisthis.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 

【上篇】
【下篇】

抱歉!评论已关闭.