使用 AJAX 填充选择列表 [英] Populate Select list with AJAX

查看:21
本文介绍了使用 AJAX 填充选择列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我是一个真正的 JQUERY 新手,所以请放轻松.

我想使用从 CFC 返回的数据填充 CFSELECT.这是我的工作 CFC:

<cffunction name="getDescriptions" access="remote" returnformat="json" returntype="string" output="false"><cfquery name="customDescriptions" datasource="#datasource#">选择描述来自 service_descriptions其中描述<>添加新"按描述排序</cfquery><cfset 数据 = serializeJSON(customDescriptions)><c返回数据></cffunction>

以下是从我的 CFC 中返回数据的方式:

<块引用>

---->从列表中选择<----备份维护恶意软件清除每月服务器维护网络监视警报 - 高 CPU 使用率网络监视警报 - 低CNetwatch 备份警报上的磁盘空间新员工培训执行工作站每月调整测试测试2测试3测试4测试5每周维护白名单请求

我正在努力使用我的 AJAX 代码来填充我的 CFSELECT 表单元素.

这是迄今为止我的 AJAX 所拥有的,但它不起作用.

 <脚本>$(document).ready(function CheckAjaxCall(){$.ajax({类型:'POST',url:'cfcs/get_descriptions.cfc?method=getDescriptions',数据类型:'json',缓存:假,成功:功能(自定义描述){$('##descriptionDD4').get(0).options.length = 0;$('##descriptionDD4').get(0).options[0] = new Option("--Select--", "0");$.each(描述,功能(我,项目){$('##descriptionDD4').get(0).options[$('##descriptionDD4').get(0).options.length] = new Option(item[i].Name, item[i].卷);//显示值});},//error:function(){alert("连接不可用");}});返回假;});</脚本>

任何帮助将不胜感激.谢谢.-布赖恩

解决方案

注意:默认情况下,CF 序列化查询的方式很不稳定.从长远来看,您可能希望自己滚动并返回更典型(和直观)的东西,例如结构数组.但仍然值得了解为什么您当前的代码不起作用,IMO.

问题:

正如.由于您的查询仅返回一列,因此我将它用于选项文本和值.

$.each(response.DATA, function(i, row){//获取第一列的值,即描述"变量描述=行[0];//将新选项添加​​到列表$("#descriptionDD4").append($('<option/>', {值:描述,文字:描述}));});

剩下的就是将 ajax 调用包装在一个函数中,您可以在任何需要的地方调用.但是你应该能够自己弄清楚那部分.

希望这对使用 jQuery 的远程 cffunctions 有所帮助.

So I am a real JQUERY novice, so please go easy on me.

I would like to populate a CFSELECT using data returned from a CFC. Here is my working CFC:

<cfcomponent>
<cffunction name="getDescriptions" access="remote" returnformat="json" returntype="string" output="false">
    <cfquery name="customDescriptions" datasource="#datasource#">
        select description
        from service_descriptions
        where description <>"ADD NEW"
        order by description
     </cfquery>

    <cfset data = serializeJSON(customDescriptions)>
    <cfreturn data>
</cffunction>

Here is how the data from my CFC is returned:

---->Choose from the list<----Backup MaintenanceMalware RemovalMonthly Server MaintenanceNetwatch Alert - High CPU usageNetwatch Alert - Low Disk space on CNetwatch Backup AlertNew Employee TrainingPerform monthly tune-ups on workstationsTesttest2test3test4test5Weekly MaintenanceWhite-list Request

I am strugling with my AJAX code to populate my CFSELECT form element.

<cfselect name="descriptionDD4" id="descriptionDD4">
   <option value="add_new">ADD NEW</option>
</cfselect>

Here is what I have so far with my AJAX but it doesn't work.

 <script>
       $(document).ready(function CheckAjaxCall()
            {
                $.ajax({
                    type:'POST',
                    url:'cfcs/get_descriptions.cfc?method=getDescriptions',                    
                    dataType:'json',
                    cache:false,
                    success:function(customDescriptions){ 

                $('##descriptionDD4').get(0).options.length = 0;
                $('##descriptionDD4').get(0).options[0] = new Option("--Select--", "0");        

                $.each(description, function(i,item) {
                                    $('##descriptionDD4').get(0).options[$('##descriptionDD4').get(0).options.length] = new Option(item[i].Name, item[i].roll);
                                                                                                                    // Display      Value
                            });

                            },
                            //error:function(){alert("Connection Is Not Available");}
                        });

                        return false;
                    });
            </script>

Any help would be greatly appreciated. Thanks. -Brian

解决方案

Note: The way CF serializes queries by default is wonky. In the long run you may want to roll-your-own and return something more typical (and intuitive), like an array of structures. But it is still worthwhile to understand why your current code is not working, IMO.

Issue:

As Scott pointed out, the biggest problem is that your javascript code is expecting one format, but your cfc is returning a different format. You need to change one of them, so they are both in synch. Also, as I mentioned in the comments, using cfselect does not buy you anything here, so just use a plain html select instead.

Debugging:

Before you can do anything with the response from the CFC, you need to understand the format of what it is sending back. Start simply. Just call the cffunction when the page loads and log the response to the console. You can wrap everything up in a function later, after it is working.

<script type="text/javascript">
$(document).ready(function(){
    // Important: Must append the parameter "&returnformat=json"
    $.ajax({
       url: 'cfcs/get_descriptions.cfc?method=getDescriptions&returnformat=json'
       , dataType: 'json'
       , success: function(response){
           console.dir(response);
       },
       error: function(msg){
           console.log(msg);
       }
    })
}); 
</script>

Using FF's web console, you will see the result is a structure containing two keys: COLUMNS and DATA.

DATA is a multi-dimensional array, containing your query results. It is indexed by row and column number. You can loop through it, same as in CF. The only difference is the index will be zero based (and of course key names are case sensitive in JS). Add the code below to your success function and you will see the query values displayed in the Web Console.

 // display values for debugging purposes
 for (var i = 0; i < response.DATA.length; i++){
    console.log("value in row ["+ i +"] column [0] = "+ response.DATA[i][0]);
 }

Usage:

Once you understand how to access the data, it is just a matter of using it to populate the list. You can either use the for loop to append options individually, or plug the DATA array into the $.each function, using the method described here. Since your query only returns a single column, I used it for both the option text and value.

$.each(response.DATA, function(i, row){
            // get value in first column ie "description"
            var description = row[0];

            // append new option to list
            $("#descriptionDD4").append($('<option/>', { 
                    value: description,
                    text : description 
            }));
        });

All that is left is to wrap the ajax call in a function you can call wherever needed. But you should be able to figure that part out on your own.

Hopefully this shed a little light on working with remote cffunctions from jQuery.

这篇关于使用 AJAX 填充选择列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆