使用 JQuery UI 滑块选择字段后从 JSON 获取数据

Obtain data from JSon after choosing a field with a JQuery UI slider(使用 JQuery UI 滑块选择字段后从 JSON 获取数据)

本文介绍了使用 JQuery UI 滑块选择字段后从 JSON 获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个包含 JQuery UI 滑块的网页,您可以在其中选择年份.在滑块停止事件之后,我希望网页显示与我选择的年份相关的 JSon 文件中的数据.首先,我想知道这样做是否可行(我使用的是 HTML + CSS + JavaScript).

I'm doing a webpage that contains a JQuery UI slider, where you can select a year. After the stop event of the slider, I want the webpage to show the data from a JSon file related to the year I have chosen. First, I would like to know if doing this dinamically is possible (I'm using HTML + CSS + JavaScript).

其次,这里是滑块的停止事件:

And second, here is the stop event of the slider:

    stop: function (event, ui) {
        alert('Stopped at ' + ui.value);            

        $.getJSON('winners.json', function(winners) {
            var output=" ";

            output+=winners.driver[ui.value].name;
            document.getElementById("winner").innerHTML=output;
        });
    }

警报正确显示在滑块中选择的年份.

The alert shows properly the year selected in the slider.

winners.json 有 2 个字段(年份、名称),driver 是 JSon 数组的名称,winners 是 HTML 中的占位符

winners.json has 2 fields (year, name), driver is the name of the JSon Array and winner is a placeholder in the HTML

推荐答案

从你对 winners.json 的描述,听起来你有一个名为 driver 的对象,其中包含数组.数组中的每个对象都有两个字段:yearname.然后,您尝试访问 name 字段,就像它嵌套在 year 字段中一样......而不是作为 year 场.如果是这种情况,您需要重新构建 winners.json 文件以匹配您的代码,或者更简单...更改您的代码以正确访问 name.

From your description of winners.json, it sounds like you have an object named driver that contains an array. Each object in the array has two fields: year and name. Then, you are trying to access the name field as if it was nested within the year field...instead of being a sibling of the year field. If this is the case, you either need to restructure your winners.json file to match your code, or easier...change your code to access the name correctly.

如果他们是兄弟姐妹,你可以这样做:

If they are siblings, you could do something like this:

for (var i=0,len=winners.driver.length; i < len; i++) {
    if(winners.driver[i].year === ui.value){
        output += winners.driver[i].name;
    }
}

另外,请确保 winners.json 文件已上传到您的网络服务器,并且您在拨打电话时指定了正确的路径.根据您所拥有的,它将在与您进行调用的 HTML 文件相同的目录中查找.

Also, make sure that the winners.json file is uploaded to your web server, and you are specifying the correct path when you make your call. Based on what you have, it would be looking in the same directory as your HTML file that's making the call.

这篇关于使用 JQuery UI 滑块选择字段后从 JSON 获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 JQuery UI 滑块选择字段后从 JSON 获取数据

基础教程推荐