设为首页 收藏本站
查看: 428|回复: 0

[经验分享] Sharepoint学习笔记—ECMAScript对象模型系列-- 6、使用ECMA操作列表项对象(list item)

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-9-25 11:45:39 | 显示全部楼层 |阅读模式
  前面我们使用ECMAScript对象模型操作website对象,list对象,这里我们进一步看看如何使用模型来操作列表项List item对象。
  实践之前,首先需要在我们的Sharepoint网站上创建一个名为product的list,如下图:
DSC0000.jpg   
    一、添加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 &#8216;myfolder&#8217;
    //in the product list the url will be  &#8216;/myweb/Lists/product/myfolder&#8217;.
    //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 &#8216;SP.FileSystemObjectType&#8217;.
    //The addProduct method below takes few arguments that represents the product list&#8217;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>  
DSC0001.jpg
  四、查找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 &#8216;include&#8217;)
    // 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;
            //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;
        //            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> DSC0002.jpg
  
    五、更新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&#8217;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>  
DSC0003.jpg
  
  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-118646-1-1.html 上篇帖子: SharePoint Portal Server与SharePoint Services之间的关系 下篇帖子: Sharepoint学习笔记—Site Definition系列--7、如何在Site Definition中引入Master Page (1、Master P
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表