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

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

问题描述

所以我是一个真正的JQUERY新手,所以请容易在我身上。



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

 < cfcomponent> 
< cffunction name =getDescriptionsaccess =remotereturnformat =jsonreturntype =stringoutput =false>
< cfquery name =customDescriptionsdatasource =#datasource#>
从service_descriptions
中选择描述
其中description<>ADD NEW
按说明订单
< / cfquery>

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



将返回我的CFC中的数据:


---->从列表中选择<删除服务器MaintenanceNetwatch警报 - 高CPU使用率网络警报 - 低
CNetwatch上的磁盘空间备份警报新员工培训
工作站上的每月调整Testest2 test3test4test5Weekly
MaintenanceWhite列表请求


我遇到了我的AJAX代码填充我的CFSELECT表单元素。

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

这是我到目前为止与我的AJAX,但它不工作。

 < 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);
//显示值
});

},
//错误:function(){alert(Connection Is Not Available);}
});

return false;
});
< / script>

任何帮助将非常感谢。谢谢。
-Brian

解决方案

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



问题:



作为。由于您的查询只返回一个列,因此我将其用于选项文本和值。

  $。 DATA,function(i,row){
//获取第一列中的值,即description
var description = row [0];

//追加新选项list
$(#descriptionDD4)。append($('< option />',{
value:description,
text:description
}))
});

剩下的就是将ajax调用包装在一个函数中,但你应该能够自己计算出这一部分。



希望这有助于使用jQuery的远程缓存。


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天全站免登陆