将数据从 JSON 数组复制到 JS 对象以实现 jQuery 自动完成
我正在尝试使用 jQuery 中的自动完成插件来允许用户使用文本字段快速搜索人名并返回他们的 Facebook 用户 ID。 Facebook 提供的 JSON 是这样的:
{
"data":[
{
"name":"Emma Alexander",
"id":"8110855"
},
{
"name":"Dave Suckow",
"id":"19546358"
},
{
"name":"Jessica Willits",
"id":"45734687"
}
]
}
但是,我想在本地进行搜索,而不是每次都检索 Facebook JSON,所以我认为我需要将所有名称和 ID 复制到本地 JavaScript 对象中(我认为这是最好的方法吗?),然后使用 jQuery 来搜索这些名称。当用户从文本字段中选择一个姓名时,它将调用另一个函数并向其传递所选人员的 Facebook ID。
但是,我不确定这是否是最好的方法,或者我将如何真正实施它。
如果有人可以提供一些小代码示例,特别是将数据从 Facebook 的 JSON 复制到本地 Javascript 对象,然后搜索该对象,我们将不胜感激! :)
多谢
I'm trying to use the Autocomplete plugin in jQuery to allow a user to search for a person's name quickly using a text field and return their Facebook user id. The JSON that Facebook provides is along these lines:
{
"data":[
{
"name":"Emma Alexander",
"id":"8110855"
},
{
"name":"Dave Suckow",
"id":"19546358"
},
{
"name":"Jessica Willits",
"id":"45734687"
}
]
}
However, I'd like to do the searching locally, rather than retrieving Facebook JSON every time, so I think I need to copy all of the names and IDs into a local JavaScript Object (I think that's the best way to do it?) and then use jQuery to search through those names instead. When the user selects a name from the text field, it will call another function and pass it the selected person's Facebook ID.
However, I'm not sure if this is the best way, or how I would really go about implementing it.
If anybody could offer a couple of small code examples, especially for copying the data from Facebook's JSON to a local Javascript object and then searching through that object, it would be massively appreciated! :)
Thanks a lot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
嗯..你可以这样做...
数组
name
和id
将包含从 JSON 中获取的所有名称和 id,并搜索新值中的所有值创建数组...这是一种方法...另一种方法是您可以将返回的 JSON 保存在变量jsonval
中,然后每次使用用于将值推入数组的 for 循环进行搜索...Hmm..You could do something like this...
The arrays
name
andid
will contain all the names and ids fetched from the JSON and searh all the values in the new arrays created...Thats one way... the other is you could save the JSON returned in the variablejsonval
and then every time search using the for loop that was used to push the values into an array...我认为你最好每次都调用 fb json,因为搜索之间可能会发生一些变化。这就是说,如果你在加载时进行了 ajsx 调用,你可以像这样在开始时设置一个 var,
然后一旦你进行了 ajax 调用并且你得到了 json 数据,只需将变量设置为 dataresult bob 你叔叔
有意义吗?
I think your better off to just call the fb json every time because something could change between searching. that said if you made your ajsx call on load you could just set a var at the begining like this
then once your ajax call is made and you get your json data just set the variable to the dataresult bobs your uncle
make sense ?
未经测试,但以下函数采用搜索字符串和数据对象并在名称字段中进行搜索,并返回用户的
id
,如果未找到匹配项则返回 null。Not tested, but the following function takes a search string and the data object and searches in the name field, and returns the user's
id
, or null if no match found.