javascript - 在页面加载时通过 JQUERY 获取 SelectList 值

标签 javascript jquery coldfusion

我有一个 <select>通过 AJAX 在页面加载时动态填充的列表。我试图在加载页面时以及在用户实际选择默认选择以外的其他内容之前找出初始选择的值。

获取值后,我试图将其传递给名为 PopulateCustomerAlertDIV() 的自定义函数.这是我目前所拥有的:

HTML:

 <cfselect name="company_name" id="company_name" tabindex="0" 
      onchange="PopulateCustomerAlertDIV();" >
      <option>#customers.company_name#</option>
 </cfselect> 

Javascript(填充列表)

<!--- Retrieves list of customers --->
<script>
$(document).ready(function () {       
    //populate the vehicle select list
    $.ajax({
       url: 'cfcs/get_customers.cfc?method=getData&returnformat=json',
       dataType: 'json',
       success: function(response){
           console.log('Success');
           $.each(response.DATA, function(i, row){
            // get value in first column ie "description"
            var company_name = row[0];

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

        });
       },
       error: function(msg){
           console.log(msg);
       }
    })
    populateSalesTax();
    console.log('Sales Tax Function Ran from Customer Query Function');
});
</script>

Javascript(填充 DIV):

<script>
function PopulateCustomerAlertDIV(){
    // Populate the customer alert DIV based on the customer selection
    console.log( $("##company_name2>option:selected").attr("Value") );

    $.ajax({
        url:'cfcs/customerAlertDIV.cfc?method=getAlert&returnformat=json',
        dataType: 'json',
        data: { company_name: $("##company_name>option:selected").attr("Value") },
        success: function(obj) {
            JSON.stringify(obj);//to string
            console.log(obj.alert);
            $("##CustomerAlertDIV").html( '<div style="width:80%" align="center"> <br /> <br />' + obj.alert + ' <br /> <br /> </div>' );
                if(obj.alert_priority == 'high' ) {
                    $('##CustomerAlertDIV').removeClass().addClass('alert_error');
                } 
                else if (obj.alert_priority == 'medium' ){
                    $('##CustomerAlertDIV').removeClass().addClass('alert_warning');
                }
                else if(obj.alert_priority == 'low' ){
                    $('##CustomerAlertDIV').removeClass().addClass('alert_info');
                }

            },
        error: function(req, err){ 
                $("##CustomerAlertDIV").html("");
                $('##CustomerAlertDIV').removeClass().addClass('');
                console.log('error'); }
      });
}

$(document).ready(function() {
    console.log('My Var: ' + x);
    PopulateCustomerAlertDIV();
    console.log('Customer DIV Function Ran');
    populateSalesTax();
    console.log('Sales Tax Function Ran from Document Ready');
});
</script>

Get_Customers.cfc

<cfcomponent>
    <cffunction name="getData" access="remote" returntype="query">
        <!---Get Customers --->
        <cfquery name="data" datasource="#datasource#">
        select company_name
        from customer_table
        order by company_name ASC
        </cfquery>

        <!--- Return results --->
        <cfreturn data>
    </cffunction>

    <!---Get Customer Sales Tax Info --->
    <cffunction name="getSalesTax" access="remote" returntype="query">
        <cfargument name="company_name" type="any" required="true">

        <!--- localize function variables --->
        <cfset var dataDetail = "">
        <cfoutput>
        <cfquery name="dataDetail" datasource="#datasource#">
            SELECT tax_rate
            FROM   customer_table
            <!--- adjust cfsqltype if needed --->
            WHERE company_name = <cfqueryparam value="#ARGUMENTS.company_name#" cfsqltype="cf_sql_varchar">
        </cfquery>
        </cfoutput>

        <cfreturn getSalesTax.tax_rate>
    </cffunction>  
</cfcomponent>

CustomerAlertDIV.cfc

<cfcomponent>
    <cffunction name="getAlert" access="remote" returntype="any">
        <cfargument name="company_name" type="any" required="true">

        <!--- localize function variables --->
        <cfset var dataDetail = "">

        <cfquery name="getID" datasource="#datasource#" >
            select  customer_id
            from    customer_table
            where   company_name = <cfqueryparam value="#ARGUMENTS.company_name#" 
                                    cfsqltype="cf_sql_varchar">
        </cfquery> 
        <cfquery name="dataDetail" datasource="#datasource#">
            SELECT  ID, alert, alert_priority
            FROM    customer_alerts
            WHERE   customer_id = <cfqueryparam value="#getID.customer_id#" cfsqltype="cf_sql_varchar"> AND alert_status = 'on'
        </cfquery>

        <cfoutput query="dataDetail">
            <cfset obj = {
                "alert" = alert,
                "alert_priority" = alert_priority               
             } />

        <cfprocessingdirective suppresswhitespace="Yes"> 
            <cfoutput>
                #serializeJSON(obj)#
            </cfoutput>
        </cfprocessingdirective>
        </cfoutput>
    </cffunction>
</cfcomponent>

最佳答案

(聊天摘要)

简答:

只是为了澄清原来的问题:它是由时间问题引起的。该代码使用多个 ajax 调用,它们是异步的。结果,刷新 DIV 的函数试图在公司列表填充之前 获取选定的公司。显然,解决方案是等到它被填充之后。然后刷新DIV。

更长的答案:

原始代码使用了一个 <cfselect bind...> ,或 ExtJS,使用与 jQuery 不同的事件模型。 JQuery 的 document.ready事件实际上是在 ExtJS 加载选择列表之前触发的。因此,当 PopulateCustomerAlertDIV()试图捕获“选定的”公司:

   $.ajax({
        url:'cfcs/customerAlertDIV.cfc?method=getAlert&returnformat=json',
        data: { company_name: $("##company_name>option:selected").attr("Value") },
        .. 
   });

...结果为空/未定义。所以它实际上并没有将有效的 company_name 传递给 CFC。这就是为什么 <div>未正确填充。

<script>
$(document).ready(function() {
   //...
   // 1st: $.ajax() call to populate select list
   PopulateList();
   // 2nd: populate div with selected company
   PopulateCustomerAlertDIV();
   //...
});
</script>

后面的代码使用 jQuery 来填充列表而不是“绑定(bind)”。这是更好的 IMO,因为它不混合事件模型。但是,它仍然存在轻微的时间问题。

第一个函数使用 $.ajax()调用以填充公司列表。 $.ajax()默认情况下调用是异步的。尽管 PopulateCustomerAlertDIV()第二个函数被调用,不能保证第一个函数在启动时会完成执行。所以最终,PopulateCustomerAlertDIV()在填充公司列表之前仍在尝试访问所选公司。

解决方案是调用 PopulateCustomerAlertDIV()在填充公司列表后:正如 Mike 建议的那样,在 success() 中ajax调用的方法。 (虽然不需要修改函数参数)。

请记住,您还可以通过使用同步 ajax 调用来解决问题,或者完全放弃 ajax 并使用基本的 cfoutput 循环填充列表。那么时机就不是问题了。但是,这些选项各有利弊。

关于javascript - 在页面加载时通过 JQUERY 获取 SelectList 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28891046/

相关文章:

javascript - 将单选按钮更改为图像会导致 jquery 验证丢失

javascript - 如何在 blueimp jQuery 文件上传上使用自己的文件处理程序?

iis - 间歇性的 ColdFusion 404 错误页面,有时显示连接重置/中断,有时显示错误页面

ColdFusion - 替换值以格式化段落的最佳方法是什么?

javascript - 我们是否应该使用 JavaScript 和 CGI​​ 变量从我们的访问者报告中清除机器人?

javascript - moment.js 和meteor,使用存储时刻的问题

javascript - yyyy-mm-dd 的正则表达式

javascript - 使用 Gatsby 和模板进行分页

java - 如何从 JSP 访问 JavaScript 中的 Java 对象

jquery - 为什么这个 jQuery 对象未定义?