jQuery 使用 Javascript / KendoUI 自动完成渲染数据时出错 - 对象 #<Object> 没有方法“切片” - 如何解决?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17836235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error rendering data with Javascript / KendoUI autocomplete - Object #<Object> has no method 'slice' - how to resolve?
提问by ElHaix
I am following the Using Kendo UI with MVC4 WebAPI OData and EFarticle. After installing KendoUI and making sure all references are set, I type in three characters, and get the following error:
我正在关注将Kendo UI 与 MVC4 WebAPI OData 和 EF 一起使用的文章。安装 KendoUI 并确保设置了所有引用后,我输入了三个字符,并收到以下错误:
Uncaught TypeError: Object # has no method 'slice'
未捕获的类型错误:对象 # 没有方法“切片”
Root of the Problem
问题的根源
To save reading through the updates: Through debugging I found that the issue is that JS is expecting to parse an array, where it isn't available in the data - at the root. In the data hierarchy, it's one level in.
为了节省阅读更新:通过调试,我发现问题是 JS 期望解析一个数组,而它在数据中不可用 - 在根。在数据层次结构中,它是一级。
Original Problem
原问题
I cleaned up kendo.web.min.js and the error is occuring around line 3498:
我清理了 kendo.web.min.js 并且错误发生在第 3498 行附近:
success: function (n) {
var i = this,
r = i.options;
return i.trigger(wt, {
response: n,
type: "read"
}), n = i.reader.parse(n), i._handleCustomErrors(n) ? (i._dequeueRequest(), t) : (i._pristine = et(n) ? e.extend(!0, {}, n) : n.slice ? n.slice(0) : n, i._total = i.reader.total(n), i._aggregate && r.serverAggregates && (i._aggregateResult = i.reader.aggregates(n)), n = i._readData(n), i._pristineData = n.slice(0), i._data = i._observe(n), i._addRange(i._data), i._process(i._data), i._dequeueRequest(), t)
The Kendo UI widgets are loading just fine as well as the css:
Kendo UI 小部件和 css 一样加载得很好:
<link href="~/Content/kendo/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo/kendo.default.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/kendo/kendo.web.min.js"></script>
<script src="~/Scripts/kendo/kendo.aspnetmvc.min.js"></script>
<script src="~/Scripts/appScripts.js"></script>
And I am seeing the same error both with using the Razor MVC helper/extension:
我在使用 Razor MVC 帮助程序/扩展时看到了同样的错误:
@(Html.Kendo().AutoComplete()
.Name("userAutoComplete") // specifies the "id" attribute of the widget
.DataTextField("USERNAME")
.DataSource(source =>
{
source.Read(read =>
{
read.Url("/api/user");
})
.ServerFiltering(true); // if true, the DataSource will not filter the data on the client
}
)
)
and through directly through JS:
并直接通过JS:
/// <reference path="kendo/kendo.aspnetmvc.min.js" />
/// <reference path="kendo/kendo.core.min.js" />
/// <reference path="kendo/kendo.autocomplete.min.js" />
/// <reference path="kendo/kendo.web.min.js" />
$(document).ready(function () {
// load up KendoUI
// gets data from /api/user
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/api/user"
}
}
});
$("#userSearch").kendoAutoComplete({
dataSource: dataSource,
dataTextField: "USERNAME",
minLength: 3
});
$("#userSearch").on('input', function () {
console.log($("#userSearch").val());
});
}); // $(document).ready()
I'm sure this is something simple that I may be missing. I have tried both with the web and all js files.
我确定这是我可能遗漏的一些简单的东西。我已经尝试过网络和所有 js 文件。
Any assistance would be appreciated.
任何援助将不胜感激。
-- UPDATE --
- 更新 -
The only real html missing from that content is the <input id="userAutoComplete" />
该内容中唯一缺少的真正的 html 是 <input id="userAutoComplete" />
I created a brand new solution and a very simple view, based on one of the Kendo UI examples that gets JSON data from http://api.geonames.org, and getting the same error.
我创建了一个全新的解决方案和一个非常简单的视图,基于从http://api.geonames.org获取 JSON 数据的 Kendo UI 示例之一,并得到相同的错误。
I thought that using the newest JS library (//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
may have been causing a problem so I tried the 1.7 lib. Same issue:
我认为使用最新的 JS 库(//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
可能导致问题,所以我尝试了 1.7 库。同样的问题:
@using Kendo.Mvc.UI
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" href="@Url.Content("~/Content/kendo.common.min.css")">
<link rel="stylesheet" href="@Url.Content("~/Content/kendo.default.min.css")">
<link rel="stylesheet" href="@Url.Content("~/Content/kendo.dataviz.min.css")">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script src="@Url.Content("~/Scripts/kendo.web.min.js")"></script>
<script src="@Url.Content("~/Scripts/kendo.aspnetmvc.min.js")"></script>
<script src="@Url.Content("~/Scripts/kendo.dataviz.min.js")"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#autoComplete").kendoAutoComplete({
minLength: 6,
dataTextField: "title",
filter: "contains",
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "http://api.geonames.org/wikipediaSearchJSON",
data: {
q: function () {
return $("#autoComplete").data("kendoAutoComplete").value();
},
maxRows: 10,
username: "demo"
}
}
},
schema: {
data: "geonames"
}
}),
change: function () {
this.dataSource.read();
}
})
});
</script>
</head>
<body>
<div>
<input id="autoComplete"/>
</div>
</body>
</html>
-- UPDATE --
- 更新 -
Using the code above, I went back and tried it again - it worked fine. After trying several more times, I experienced the same issue. This was due to the valid JSON data changing to the following:
使用上面的代码,我返回并再次尝试 - 它工作正常。多次尝试后,我遇到了同样的问题。这是由于有效的 JSON 数据更改为以下内容:
{"status":{"message":"the daily limit of 30000 credits for demo has been exceeded. Please use an application specific account. Do not use the demo account for your application.","value":18}}
... which lead me to look at the formatting of the data coming from my API (looking at it in Fiddler:
...这让我看到了来自我的 API 的数据格式(在 Fiddler 中查看它:
Instead of:
代替:
JSON ---{... data...
JSON ---{... 数据...
it's
它是
JSON
---$id=1
---$values
------{}
---------$id=2
---------CREATEDATETIME...
[email protected]
---------GROUPS
------------$id=...
------------$id=...
---------USERNAME=someusername
------{}
---------$id=4
.
.
.
So the error is caused by the array not being accessible where the it's expected - instead of the root, it's one level deep.
因此,错误是由无法在预期的位置访问数组引起的 - 而不是根,而是一层深。
How do I get data binding to the one-level-deep rather than the root of the JSON object?
如何将数据绑定到一层深度而不是 JSON 对象的根?
Thanks.
谢谢。
采纳答案by ElHaix
The solution for this was to traverse the data hierarchy by describing the result format.
对此的解决方案是通过描述结果格式来遍历数据层次结构。
Since the array is contained in $values, I used the following data source/schema definition:
由于数组包含在 $values 中,我使用了以下数据源/模式定义:
// gets data from /api/user
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/api/user"
}
},
schema: { // describe the result format
data: function(data) { // the data which the data source will be bound to is in the values field
console.log(data.$values);
return data.$values;
}
}
});
One thing that would be nice is to be able to add a data schema type in the Razor helper - which doesn't seem to be supported at this time.
一件好事是能够在 Razor 助手中添加数据模式类型 - 目前似乎不支持。
Thus, the following still would not work:
因此,以下仍然不起作用:
@(Html.Kendo().AutoComplete()
.Name("userAutoComplete") // specifies the "id" attribute of the widget
.Filter("startswith")
.Placeholder("Type user name...")
.DataTextField("USERNAME")
.DataSource(source =>
{
source:
source.Read(read =>
{
read.Url("/api/user");
})
.ServerFiltering(true); // if true, the DataSource will not filter the data on the client
}
)
)
回答by Xanothos
I had the same error with a ComboBox that I was using as an autocomplete. In my controller, the return statement was
我在用作自动完成功能的 ComboBox 上遇到了同样的错误。在我的控制器中,返回语句是
return Json(model.ToDataSourceResult(dataSourceRequest), JsonRequestBehavior.AllowGet)
which I changed to
我改成
return Json(model, JsonRequestBehavior.AllowGet)
This provided the array at the root level instead of one level deep for me.
这为我提供了根级别的数组,而不是深一层。
回答by brittongr
This worked for me:
这对我有用:
var dataSource = new kendo.data.DataSource({
transport: {
read:
{
url: "api/dashboard"
}
},
schema: {
**data: function (data)
{
return [data];
}**
}
});
My response wasn't an array, i was returning from the server a response object like this:
我的响应不是一个数组,我从服务器返回一个像这样的响应对象:
{"Field1":0,"Field2":0,"Field3":0}
回答by El Bayames
thanks "brittongr"...that worked for me too. but in my case it is not right, I was building a chart, a chart need an array of course, so instead of altering the schema by converting my Json data to an array I just returned from my action a list having one element. Something like this below.
感谢“britongr”……这对我也有用。但在我的情况下这是不对的,我正在构建一个图表,一个图表当然需要一个数组,所以我没有通过将我的 Json 数据转换为数组来改变模式,而是从我的操作中返回一个包含一个元素的列表。像下面这样的东西。
Random rand = new Random();
int numIterations = 0;
numIterations = rand.Next(1, 1200);
List aux = new List<graphicDataItem>();
aux.Add(new graphicDataItem { ColumnTotal = 1200, ColumnActives = numIterations, ColumnInactives = 1200 - numIterations, ColumnApprovedByMembers = 250, ColumnApprovedByAssoc = 300, XAxisData = DateTime.Now.Year });
return Json(aux, JsonRequestBehavior.AllowGet);
I have "graphicDataItem" type defined on my Entities folder, but is easy to get by looking at the way it is instantiated within the code.
我在 Entities 文件夹中定义了“graphicDataItem”类型,但通过查看它在代码中的实例化方式很容易获得。
回答by user2929775
i change for this, and this work for me:
我为此而改变,这对我有用:
@(Html.Kendo().AutoComplete()
.Name("productAutoComplete") //The name of the autocomplete is mandatory. It specifies the "id" attribute of the widget.
.DataTextField("myfield") //Specifies which property of the Product to be used by the autocomplete.
.DataSource(source =>
{
source.Custom()
.Type("aspnetmvc-ajax")
.Transport(transport=>
{
transport.Read("MyAction", "Control");
})
.Schema(schema=>schema.Data("Data").Total("Total"))
.ServerFiltering(true); //If true the DataSource will not filter the data on the client.
})
)
)