使用 Javascript/Jquery 和 Json 数据在单击时填充选择框选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10233464/
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
Populate Select box options on click with Javascript/Jquery with Json data
提问by InspiredBy
I'm still learning Jquery and a bit confused with the task I have on my hands.
我仍在学习 Jquery 并且对我手头的任务有点困惑。
Seems like a simple task... I have a box that I want to populate with Options on click. I don't want it to be populated on page load, only when someone actually requests to see the list. Also it has to be populated only once. I really dont want the request to go out EVERY time someone expands the list.
似乎是一项简单的任务......我有一个框,我想在单击时填充选项。我不希望它在页面加载时填充,只有当有人实际请求查看列表时才填充它。此外,它必须只填充一次。我真的不希望每次有人扩展列表时请求都会消失。
I imagine that I'll probably have a function call in my Select element
我想我的 Select 元素中可能会有一个函数调用
<select id="usersList" name="usersList" onclick="getUsers()">
And then have a Javascript getUsers() function make a call to my Json GetUsers() ActionMethod to get that list. How ?
然后让 Javascript getUsers() 函数调用我的 Json GetUsers() ActionMethod 以获取该列表。如何 ?
Something like...?
就像是...?
function getUsers()
{
getJSON("/Users/GetUsers", null, function (data){}
}
or JQuery?...
还是JQuery?...
$("usersList").click(
$.getJSON("/Users/GetUsers", null, function (data) {}
)
I should mention that I saw this post: populate selectlist with json data in JQuery when the selectlist is loaded (not the document)
我应该提到我看到了这篇文章: 在加载选择列表(不是文档)时,在 JQuery 中使用 json 数据填充选择列表
But I need help putting it all together please. Thank you in advance!
但我需要帮助把这一切放在一起。先感谢您!
回答by Spencer Ruport
Here is the javascript I would use to populate the select box.
这是我用来填充选择框的 javascript。
$.getJSON("/Users/GetUsers", null, function(data) {
$("#UsersList option").remove(); // Remove all <option> child tags.
$.each(data.Users, function(index, item) { // Iterates through a collection
$("#UsersList").append( // Append an object to the inside of the select box
$("<option></option>") // Yes you can do this.
.text(item.Description)
.val(item.Id)
);
});
});
I would recommend that you trigger this on the page load and not when the user clicks the select box. jQuery AJAX is asynchronous by default (as it should be) so there will be a moment or two where the select box will be empty and this may greatly confuse the user.
我建议您在页面加载时触发此操作,而不是在用户单击选择框时触发。默认情况下,jQuery AJAX 是异步的(应该是这样),因此有一两次选择框将是空的,这可能会极大地混淆用户。
Was this the extent of your question or did you need assistance with the MVC side as well? If you're using ASP.Net MVC there is actually a specific result type of JsonResult which makes creating JSON controller methods a bit simpler since they don't require corresponding views. It also allows you to use anonymous data structures which makes method specific projections a bit simpler.
这是您的问题的范围,还是您也需要 MVC 方面的帮助?如果您使用的是 ASP.Net MVC,实际上有一个特定的结果类型 JsonResult,这使得创建 JSON 控制器方法更简单一些,因为它们不需要相应的视图。它还允许您使用匿名数据结构,这使得特定于方法的投影更简单一些。
EDITHere is the basic method for returning a JSON structure the jQuery code above will understand. Note that the properties u.Username
and u.ID
depend on your Users object.
编辑这里是返回 JSON 结构的基本方法,上面的 jQuery 代码将理解。请注意,属性u.Username
和u.ID
取决于您的用户对象。
[HttpPost]
public JsonResult GetUsers() {
return Json(new {
Users = from u in _usersRepository.Get()
select new { Description = u.Username, ID = u.ID }
});
}
I would recommend however that you abandon this approach as soon as possible and go with a standard JSON message structure. The one I use is something like this:
但是,我建议您尽快放弃这种方法并使用标准的 JSON 消息结构。我使用的是这样的:
{
Success: bool,
LoggedIn: bool,
ClientErrors: [
{ Number: int, Description: string, Parameter: string },
{ Number: int, Description: string, Parameter: string }...
],
ServerErrors: [
{ Id: int, Message: string },
{ Id: int, Message: string }...
],
Data: {}
}
Here are a few reasons for doing this:
以下是这样做的几个原因:
- Make no mistake, your JSON method library is a protocol of sorts and as such it benefits from a standard header.
- Error handling benefits the most from this. Having a consistent method for letting the user know something went wrong is invaluable down the road.
- Differentiating between client errors (bad username, incorrect password, etc) and server errors (database offline) is very important. One the user can fix, the other they cannot.
- Client Errors should return not only a message but the parameter in the method which cause it (if it applies) so that you can easily display these error messages next to the appropriate input fields.
- Client Errors should also provide a unique number (per method) which identifies the error. This allows for multilingual support.
- Server errors should provide the Id of the error which was logged. This way you can allow the user to contact support and reference the particular error they are running into.
- The loggedin boolean allows any page which uses methods that require authentication to easily redirect the user back to the login screen if necessary since a redirect action result of a JSON method will have no effect.
- Finally the Data field is where the method specific data should be provided.
- 毫无疑问,您的 JSON 方法库是一种协议,因此它受益于标准标头。
- 错误处理从中受益最大。有一个一致的方法让用户知道出了什么问题是非常宝贵的。
- 区分客户端错误(错误的用户名、错误的密码等)和服务器错误(数据库离线)非常重要。一个用户可以修复,另一个他们不能。
- 客户端错误不仅应返回一条消息,还应返回导致该消息的方法中的参数(如果适用),以便您可以轻松地在适当的输入字段旁边显示这些错误消息。
- 客户端错误还应该提供一个唯一的编号(每个方法)来标识错误。这允许多语言支持。
- 服务器错误应提供记录的错误的 ID。通过这种方式,您可以允许用户联系支持人员并参考他们遇到的特定错误。
- 登录布尔值允许任何使用需要身份验证的方法的页面在必要时轻松地将用户重定向回登录屏幕,因为 JSON 方法的重定向操作结果将无效。
- 最后,数据字段是应该提供方法特定数据的地方。
By no means should you consider my structure as theway to do it. Clearly your application needs may differ greatly from mine. Consistency, more than any particular structure is the lesson here.
你绝不应该将我的结构视为实现它的方式。显然,您的应用程序需求可能与我的有很大不同。一致性,比任何特定结构更重要的是这里的教训。
EDIT: 06/01/2016- Seeing as people are still looking at this answer. With regard to populating the drop down I would recommend looking into using a two way binding framework. Personally I prefer Knockout.JS for how easy and lightweight it is although Angular.JS would do the job as well. Aside from that the rest of this answer is still fairly up to date.
编辑:06/01/2016- 看到人们仍在看这个答案。关于填充下拉菜单,我建议考虑使用双向绑定框架。就我个人而言,我更喜欢 Knockout.JS,因为它是多么容易和轻量级,尽管 Angular.JS 也可以完成这项工作。除此之外,这个答案的其余部分仍然是最新的。
EDIT: 8/10/2016- Code was missing a comma.
编辑:2016年 8 月 10 日 - 代码缺少逗号。
回答by veeTrain
I would use the jQuery option.
我会使用 jQuery 选项。
// You are missing the new anonymous function call
$("#usersList").click(function() {
// If the select list is empty:
if ($(this).find("option").size() > 0) {
// Documentation on getJSON: http://api.jquery.com/jQuery.getJSON/
$.getJSON("/Users/GetUsers.php", null, function (data) {
$.each(data.items, function(i,item){
// Create and append the new options into the select list
$("#usersList").append("<option value="+item.id+">"+item.yourName+"</option>");
});
});
}
});
Since append()
operations are relatively 'expensive', you could also just build a string that contains the info and append it just once like this:
由于append()
操作相对“昂贵”,您也可以只构建一个包含信息的字符串,然后像这样附加一次:
var collaboration = "";
$.each(data.items, function(i,item){
collaboration += "<option value="+item.id+">"+item.yourName+"</option>";
});
$("#usersList").append(collaboration);
...
Here is a jsfiddlethat demonstrates how to determine if the select list is empty.
这是一个jsfiddle,演示了如何确定选择列表是否为空。