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

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

问题描述

所以,我是一个真正JQUERY新手,所以请去容易对我。

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

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

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>

下面是如何从我的CFC数据返回:

---->从列表中选择&LT; ----备份MaintenanceMalware RemovalMonthly服务器MaintenanceNetwatch警报 - 高CPU usageNetwatch警报 - 低   在CNetwatch备份AlertNew员工TrainingPerform磁盘空间   在workstationsTesttest2test3test4test5Weekly每月调整窗口   MaintenanceWhite列表请求

---->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

我strugling我的AJAX code来填充我的CFSELECT表单元素。

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>

下面是我到目前为止我的AJAX技术,但它不能正常工作。

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>

任何帮助将是很大的AP preciated。谢谢。 -Brian

Any help would be greatly appreciated. Thanks. -Brian

推荐答案

注:CF方式查询序列化默认情况下是靠不住的。从长远来看,你可能要滚你自己,并返回一些更典型的(直观的),像结构的数组。但它仍然是值得理解的为什么的你目前的code不工作,海事组织。

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.

问题:

作为<一个href="http://stackoverflow.com/questions/25553467/populate-cfselct-with-ajax/25576481#comment39902799_25553467">Scott指出,最大的问题是,你的JavaScript code期待一种格式,但您的CFC返回一个不同的格式。您需要更改其中的一个,所以他们都在同步。此外,正如我在评论中提到,使用 cfselect 不买你的东西在这里,所以只需使用一个普通的HTML 选择代替。

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.

调试:

在你可以从CFC的反应做任何事情,你需要了解它是什么发回的格式。开始简单。只需拨打 cffunction 的页面加载时,并记录响应到控制台。您可以在一个功能之后一切都包裹起来,这是工作后。

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>

使用FF的Web控制台,你会看到的结果是包含两个关键的结构: DATA

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

DATA 是一个多维数组,包含查询结果。它是通过行和列编号编制索引。你可以遍历它,一样的CF.唯一的区别是指数将是零基础的(当然,主要的名称是区分在JS大小写)。添加code以下到你的成功功能,您将看到的Web控制台中显示的查询值。

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]);
 }

用法:

一旦你了解如何访问数据时,它是用它来填充列表只是一个问题。您可以使用循环附加单独的选项,或者将 DATA 数组复制到 $。每个功能,使用这里的方法描述。由于您的查询只返回单个列,我用了这两个选项的文本和值。

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 
            }));
        });

所有剩下的包裹在一个函数可以调用任何需要的AJAX调用。但是,你应该能够明白这部分在你自己。

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.

希望这棚一盏小灯与远程cffunctions从jQuery的工作。

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

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

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