简体   繁体   English

为什么会出现“未捕获的TypeError:getEnumerator不是函数”?

[英]Why am I getting, “Uncaught TypeError: getEnumerator is not a function”?

In my Sharepoint 2010 Web Part, I've got this Javascript: 在我的Sharepoint 2010 Web部件中,我有以下Javascript:

function getListItemID(username, payeename, oList) {
    var arrayListEnum = oList.getEnumerator();

...which is called by this: ...这称为:

function upsertPostTravelListItemTravelerInfo1() {
var clientContext = SP.ClientContext.get_current();
var oList =   
  clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');

this.website = clientContext.get_web();
currentUser = website.get_currentUser();

var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);

var travelersEmail = $('traveleremail').val();

/* If this is an update, the call to getListItemID() will return a val; otherwise (an insert), get from newly instantiated ListItem.  */
listId = getListItemID(currentUser, travelersEmail, oList);

I got the basis for this code from here . 我从这里获得了此代码的基础。

But got the err listed above (" Uncaught TypeError: oList.getEnumerator is not a function "); 但是得到了上面列出的错误(“ Uncaught TypeError:oList.getEnumerator不是函数 ”);

One answer said I needed to add this: 一个答案说我需要补充一点:

<script type="text/javascript" src="/_layouts/15/sp.js" ></script>

...which I changed from "15" to "14" as that is the folder/version we're using. ...我将其从“ 15”更改为“ 14”,因为这是我们正在使用的文件夹/版本。

That not only didn't work, but was unrecognized. 这不仅无效,而且无法识别。 I then found a clue here , namely to add this: 然后,我在这里找到了一个线索,即添加以下内容:

$(document).ready(function () { ExecuteOrDelayUntilScriptLoaded(CustomAction, "sp.js"); });

...but that only an error prior to the one already shown, namely, " Uncaught ReferenceError: CustomAction is not defined " ...但是只有在已显示错误之前的错误,即“ Uncaught ReferenceError:未定义CustomAction

So what's the scoop? 那是什么呢? What is required to getEnumerator(), or otherwise retreive the ID val I need? getEnumerator()需要什么,否则获取我需要的ID val?

Here is the full code to that method, to show what I'm trying to accomplish, and how: 这是该方法的完整代码,以显示我要完成的工作以及如何完成该工作:

function getListItemID(username, payeename, oList) {
  var arrayListEnum = oList.getEnumerator();

  while (arrayListEnum.moveNext()) {
     var listItem = arrayListEnum.get_current();

     if (listItem.get_item("ptli_formPreparedBy") === username &&
         listItem.get_item("ptli_TravelersEmail") === payeename &&
         listItem.get_item("ptli_formCompleted") == false) {
       return listItem.get_id();    
     }
   }
   return '';
}

UPDATE 更新

When I tried this (first and third lines are new): 当我尝试这样做时(第一和第三行是新的):

<SharePoint:ScriptLinkID="ScriptLink1" Name="SP.js" runat="server" OnDemand="false" LoadAfterUI="true" Localizable="false"></SharePoint:ScriptLink>
<script type="text/javascript">
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);

...which was inspired by a cat here , I got, " System.Web.HttpParseException was unhandled by user code Message=The server tag is not well formed. " ...这是从这里的一只猫那里得到的启发,我得到了“ System.Web.HttpParseException未被用户代码处理Message =服务器标签格式不正确。

Personally, I don't think Sharepoint is very well formed. 就我个人而言,我认为Sharepoint的结构并不完善。 But that's (right) beside the point (no pun intended). 但是,这是正确的(没有双关语)。

Problem 1: You're calling getEnumerator on a list instead of a list item collection 问题1:您在列表而不是列表项集合上调用getEnumerator

getEnumerator() can only be called on a list item collection (not on a List object), and only after it's been populated with items by running clientContext.executeQueryAsync() 只能在列表项集合 (而不是List对象)上调用 getEnumerator() ,并且只能在通过运行clientContext.executeQueryAsync()其填充项之后调用

Problem 2: You need to call executeQueryAsync to populate the list item collection 问题2:您需要调用executeQueryAsync来填充列表项集合

When using the SharePoint JavaScript client object model, your code needs to be broken up into two parts: the first part specifies what you want to get, and involves you loading queries and commands into an SPClientContext object; 使用SharePoint JavaScript客户端对象模型时,您的代码需要分为两部分:第一部分指定要获取的内容,并涉及将查询和命令加载到SPClientContext对象中; the second part lets you manipulate the results of the query to SharePoint, and runs as an asynchronous callback of the query execution. 第二部分使您可以将查询结果处理到SharePoint,并作为查询执行的异步回调运行。

  1. Create your context, specify which lists you want to access, etc. 创建上下文,指定要访问的列表等。
  2. Run clientContext.executeQueryAsync() (where clientContext is an SP.ClientContext object), and pass in delegate functions to run on success or failure 运行clientContext.executeQueryAsync() (其中clientContext是一个SP.ClientContext对象),然后传递委托函数以在成功或失败时运行
  3. In your "onSuccess" delegate function, you can work with the results of the commands you loaded up in step 1 在“ onSuccess”委托函数中,可以使用在步骤1中加载的命令的结果

Problem 3: You won't be able to return values directly from an asynchronously executing function 问题3:您将无法直接从异步执行的函数返回值

Because step 3 above runs asynchronously, you can't get a return value from it. 由于上面的步骤3是异步运行的,因此您无法从中获取返回值。 Any logic that depends on the results that you get in step 3 needs to be moved forward in the execution chain, using function delegation and callbacks. 任何依赖于您在步骤3中获得的结果的逻辑都需要使用函数委托和回调在执行链中向前移动。

Problem 4: Inefficient filtering of list items 问题4:列表项的过滤效率低下

This is really more of a design flaw than a show-stopping problem, but instead of having your code return every item in the list, and then using JavaScript to enumerate through the results to see if the item you want is in there, you should tell SharePoint what filter options you want before it even executes the query. 这确实是一个设计缺陷,而不是显示停止的问题,但与其让代码返回列表中的每个项目,然后使用JavaScript枚举结果以查看所需的项目是否在其中,不如让代码返回列表中的每个项目在执行查询之前,告诉SharePoint您想要什么筛选器选项。 Then it'll only give you items that match your query. 然后,它只会为您提供与查询匹配的项目。

Use a CAML query for this; 为此使用CAML查询; CAML (Collaborative Application Markup Language) is an XML-based query language that SharePoint uses extensively. CAML(协作应用程序标记语言)是SharePoint广泛使用的基于XML的查询语言。 There are plenty of resources and tools for composing CAML queries, and you can even steal the CAML query from a SharePoint list view web part if you've already created a view that matches your query. 有很多资源和工具可用于构成CAML查询,如果您已经创建了与查询匹配的视图,甚至可以从SharePoint列表视图Web部件窃取CAML查询。

Example of how to query a SharePoint list using JavaScript CSOM 如何使用JavaScript CSOM查询SharePoint列表的示例

Here's an example using parts of your code: 这是使用部分代码的示例:

/* 
   ExecuteOrDelayUntilScriptLoaded(yourcode,"sp.js") makes sure 
   your code doesn't run until SP.js (the SharePoint JavaScript CSOM) 
   has been loaded
*/
ExecuteOrDelayUntilScriptLoaded(function(){
    var payeename = $('traveleremail').val();
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');

    /* Use a CAML query to filter your results */
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ptli_TravelersEmail\' /><Value Type=\'Text\'>'+payeename+'</Value></Eq></Where></Query></View>');

    /* get the list item collection from the list */
    var oListItems = oList.getItems(camlQuery);

    /* tell SharePoint to load the list items */
    clientContext.load(oListItems);

    /* execute the query to get the loaded items */
    clientContext.executeQueryAsync(
        /* onSuccess Function */ 
        Function.createDelegate(this,function(){
            /* 
               now that the query has run, you can get an enumerator 
               from your list item collection 
            */
            var arrayListEnum = oListItems.getEnumerator();
            var ids = [];
            while(arrayListEnum.moveNext()){
                var listItem = arrayListItem.get_current();
                ids.push(listItem.get_id());
            }
            alert(ids.length > 0 ? "IDs of matching items: " + ids : "No matching items found!");
        }),
        /*onFailure Function*/ 
        Function.createDelegate(this,function(sender,args){
            alert("Whoops: " + args.get_message() + " " + args.get_stackTrace());
        })
    );
},"sp.js");

The CAML query in the example code only filters on the ptli_TravelersEmail column; 示例代码中的CAML查询仅在ptli_TravelersEmail列上进行过滤; you'd need to add some <And> elements to capture the other two filter conditions you want. 您需要添加一些<And>元素来捕获所需的其他两个过滤条件。

This is what finally worked for me, thanks to Thriggle: 感谢Thriggle,这终于对我有用:

function setListItemID(username, payeename) {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');

    /* Use a CAML query to filter your results */
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ptli_TravelersEmail\' /><Value Type=\'Text\'>' + payeename + '</Value></Eq></Where></Query></View>');

    /* get the list item collection from the list */
    var oListItems = oList.getItems(camlQuery);

    /* tell SharePoint to load the list items */
    clientContext.load(oListItems);

    /* execute the query to get the loaded items */
    clientContext.executeQueryAsync(
        /* onSuccess Function */
        Function.createDelegate(this, function () {
            /* 
            now that the query has run, you can get an enumerator 
            from your list item collection 
            */
            var arrayListEnum = oListItems.getEnumerator();
            var ids = [];
            while (arrayListEnum.moveNext()) {
                var listItem = arrayListItem.get_current();
                ids.push(listItem.get_id());
            }
            if (ids.length > 0) {
                listId = ids[0];
            }
            else {
                listId = '';
            }
        }),
        /*onFailure Function*/
        Function.createDelegate(this, function (sender, args) {
            alert("Whoops: " + args.get_message() + " " + args.get_stackTrace());
        })
    );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我为什么会收到“ Uncaught TypeError:下载不是函数” - Why am I getting “Uncaught TypeError: download is not a function” 为什么会出现“未捕获的TypeError”错误? - Why am I getting 'Uncaught TypeError' error? 为什么在另一个 function 中使用时会出现“未捕获的类型错误:regex.test 不是函数”? - Why am I getting 'Uncaught TypeError: regex.test is not a function' when used inside another function? 当我将函数传递给React.js的子组件时,为什么会出现未捕获的TypeError? - Why am I getting an uncaught TypeError when I pass a function to a child component in React.js? 为什么我会收到这个错误:Uncaught TypeError: this.createLink is not a function at new Link at<anonymous> 1:9? - Why am I getting this error: Uncaught TypeError: this.createLink is not a function at new Link at <anonymous>1:9? Backbone.js 视图是否需要 jQuery 或 Zepto? (或者:为什么我会收到“未捕获的类型错误:未定义不是函数”?) - Do Backbone.js views require jQuery or Zepto? (Or: why am I getting “Uncaught TypeError: undefined is not a function”?) 为什么我收到错误“Uncaught TypeError: st.replace is not a function” - Why am I getting the error "Uncaught TypeError: st.replace is not a function" 为什么在使用Flexslider时会出现“ Uncaught TypeError”? - Why am I getting “Uncaught TypeError” when using Flexslider? 为什么我会收到 Uncaught TypeError: Assignment to constant variable? - Why am I getting the Uncaught TypeError: Assignment to constant variable? 为什么我收到TypeError X不是函数 - Why am I getting TypeError X is not a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM