JQuery自动完成远程数据(COLDFUSION) [英] JQuery AutoComplete with Remote Data (COLDFUSION)

查看:193
本文介绍了JQuery自动完成远程数据(COLDFUSION)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新手,JQuery试图从ColdFusion查询中提取远程数据以显示在我的文本框中。



我收到firebug的错误CFC:


未捕获TypeError:不能使用'in'运算符在

中搜索'453' blockquote>

我不知道这可能意味着什么。我看到从数据库中提取数据,因为我的控制台输出进一步下降,我看到我的数据:

  [{ value:1,label:Test article}] jquery-1.10.2.js:997 

任何人都可以帮助这个错误?



完整的HTML代码

  <!DOCTYPE html PUBLIC -  // W3C // DTD XHTML 1.0 Transitional // ENhttp://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> 
< html xmlns =http://www.w3.org/1999/xhtml>
< head>
< meta http-equiv =Content-Typecontent =text / html; charset = utf-8/>
< title>无标题文档< / title>

<!---自动完成脚本--->
< link href =css / jquery-ui-1.10.4.custom.css =stylesheettype =text / css>
< script src =Scripts / jquery-1.10.2.js>< / script>
< script src =Scripts / jquery-ui-1.10.4.custom.js>< / script>
<!---< script src =Scripts / auto_correct.jstype =text / javascript>< / script& --->

< script>
$(function(){
$(#searchField).autocomplete({
source:function(request,response){
$ .ajax({
url:kb / cfcs / search.cfc?method = lookupTitle& returnformat = json,
dataType:json,
data:{
searchterm:request.term
},
success:function(data){
response(data);
}
})
},
minLength:3,
select:function(event,ui){
$('#searchField')。val(ui.item.value);
$('#defaultArticleID')。val(ui.item。 label);
}
});
});
< / script>

< / head>

< body class =oneColFixCtrHdr>
...
<!---主容器--->
< div id =container>
< cfform name =didntmattermethod =post>
< label for =searchField>搜索KB文章< / label>
< cfinput type =textid =searchFieldname =searchFieldsize =30em; value =/>
< cfinput type =hiddenname =defaultArticleIDid =defaultArticleIDvalue =0/>
< / cfform>
< / div>
...

< / body>
< / html>

我的CFC

 < cfcomponent> 
< cffunction name =lookupTitleaccess =remoteoutput =no
hint =我返回标题列表returnformat =JSON>
< cfargument name =searchtermrequired =falsedefault =/>

<!---定义变量--->
< cfset var returnArray = ArrayNew(1)>

<!--- Do search --->
< cfquery name =datadatasource =#datasource#>
SELECT ID,title
FROM kbArticles
WHERE title LIKE< cfqueryparam cfsqltype =cf_sql_varcharvalue =%#arguments.searchterm#%/>
< / cfquery>

<!--- Build result array --->
< cfloop query =data>
< cfset titleStruct = structNew()/>
< cfset titleStruct ['value'] = ID />
< cfset titleStruct ['label'] = title />

< cfset arrayAppend(returnArray,titleStruct)/>

<!---并返回--->
< cfreturn returnArray />
< / cffunction>
< / cfcomponent>

UPDATE



进行建议的更改时,我仍然在我的自动填充表单字段中没有收到任何数据。如果我在我的CFADMIN控制台中启用了**启用请求调试输出**,我看到这个错误:



未捕获的TypeError:无法读取未定义的属性'document' p>

当我点击控制台输出中错误旁边的链接时,显示如下:

  function writeToWindow(win){
if(document.getElementById){// NS6
// failing on< table ... 100%>对于unescape()?和失败的writeCSS没有unescape(),没有问题是ns6写出<链接>标签为css
// NS6需要unescape()或否则它写'showHide%28%27cf_debug_parameters%27,%27img_cf_debug_parameters%27%29;'为方法
//win.document.write (document.getElementById(cf_debug)。innerHTML));
//NS6.2想要它转义
win.document.write(document.getElementById(cf_debug)。innerHTML);
} else {
win.document.write(document.all ['cf_debug']。innerHTML);
}
win.document.close();
win.focus();
}


解决方案

。)



如此处所述,错误表示代码正在预期解析的JSON 对象,但传递了一个简单的字符串。 jQuery不会将您的cfc响应字符串解析为JSON对象。相反,它只是将普通字符串传递给response()函数,这会导致错误,因为该函数需要一个数组。没有自动解析响应的原因是 datatype 有错误的情况。应为:

  dataType:json//注意,大写T

另外,不要忘记 var / local 局部变量,包括查询名称。



更新:



我认为一个更简单的方法是更改cffunction参数名称为 term ,然后使用URL作为源。此外,由于您没有使用cfform的任何额外功能,因此也可以切换到纯HTML元素。

 < ; script> 
$(document).ready(function(){
$(#searchField).autocomplete({
source:/kb/cfcs/search.cfc?method=lookupTitle& return format = json,
minLength:3,
select:function(event,ui){
$('#searchField')。val(ui.item.value);
$('#defaultArticleID')。val(ui.item.label);
}
});
});
< / script>
...
< form>
< label for =searchField>搜索字段:< / label>
< input id =searchField>
< input id =defaultArticleID>
< / form>


I'm a newbie with JQuery trying to pull remote data from a ColdFusion query to show in my textbox.

I am receiving an error in firebug when calling my CFC:

Uncaught TypeError: Cannot use 'in' operator to search for '453' in

I don't know what this may mean. I can see that is pulling data from my database because further down in my console output, I see my data:

[{"value":1,"label":"Test article"}] jquery-1.10.2.js:997

Can anyone help on this error?

Full HTML code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>

    <!---Autocomplete Script --->
    <link href="css/jquery-ui-1.10.4.custom.css" rel="stylesheet" type="text/css">
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script src="Scripts/jquery-ui-1.10.4.custom.js"></script>
    <!---<script src="Scripts/auto_correct.js" type="text/javascript"></script> --->

    <script>
      $(function() {
             $( "#searchField" ).autocomplete({
                    source: function(request, response){
                        $.ajax({
                            url: "kb/cfcs/search.cfc?method=lookupTitle&returnformat=json",
                            dataType: "json",
                            data: {
                                searchterm: request.term
                            },
                            success: function(data){
                                response(data);
                            }
                        })
                    },
                    minLength: 3,
                    select: function(event, ui) {
                        $('#searchField').val(ui.item.value);
                        $('#defaultArticleID').val(ui.item.label);
                    }
                });
            });
      </script>

</head>

<body class="oneColFixCtrHdr">
  ...      
  <!--- Main Container --->
  <div id="container">
       <cfform name="doesntmatter" method="post">
           <label for="searchField">Search KB Articles</label>
           <cfinput type="text" id="searchField" name="searchField" size="30em;" value=""/> 
           <cfinput type="hidden" name="defaultArticleID" id="defaultArticleID" value="0" />
       </cfform>
  </div>
  ...

</body>
</html>

My CFC:

<cfcomponent>
    <cffunction name="lookupTitle" access="remote" output="no" 
          hint="I return a list of titles" returnformat="JSON">
        <cfargument name="searchterm" required="false" default="" />

        <!--- Define variables --->
        <cfset var returnArray =ArrayNew(1)>

        <!--- Do search --->
        <cfquery name="data" datasource="#datasource#">
            SELECT ID, title
            FROM kbArticles
            WHERE title LIKE <cfqueryparam cfsqltype="cf_sql_varchar" value="%#arguments.searchterm#%" />
        </cfquery>

        <!--- Build result array --->
        <cfloop query="data">
            <cfset titleStruct = structNew() />
            <cfset titleStruct['value'] = ID />
            <cfset titleStruct['label'] = title />

            <cfset arrayAppend(returnArray,titleStruct) />    
        </cfloop>

        <!--- And return it --->
        <cfreturn returnArray />
    </cffunction>
</cfcomponent>

UPDATE

When making the suggested changes, i still recieve no data in my autocomplete form field. If I enable ** Enable Request Debugging Output** in my CFADMIN console, I see this error:

Uncaught TypeError: Cannot read property 'document' of undefined .

When I click on the link next to the error in the console output, this is what it shows:

function writeToWindow( win ) {
    if( document.getElementById ) { // NS6
        // failing on <table ... 100%> for unescape() ?, and failing on writeCSS without unescape(), no the issue is with ns6 writing out the <link> tag for css
        // NS6 needs unescape() or else it writes 'showHide%28%27cf_debug_parameters%27,%27img_cf_debug_parameters%27%29;' for methods
        //win.document.write(unescape(document.getElementById("cf_debug").innerHTML));
        //NS6.2 wants it escaped
        win.document.write(document.getElementById("cf_debug").innerHTML);
    } else {
       win.document.write(document.all['cf_debug'].innerHTML);
    }
    win.document.close();
    win.focus();
}

解决方案

(Expanded from comments...)

As mentioned here, the error means the code was expecting a parsed JSON object, but was passed a simple string instead. jQuery is not parsing your cfc response string into a JSON object. Instead it is just passing the plain string into the response() function, which causes an error because that function expects an array. The reason the response is not parsed automatically is that datatype has the wrong case. It should be:

     dataType: "json"  // Note, upper case "T"

As an aside, do not forget to var/local scope ALL of your function local variables, including query names.

Update:

I think a simpler approach here would be to change the cffunction argument name to term then use a URL as the source. Also, since you are not using any of the extra features of cfform, may as well switch to plain html elements instead.

<script>
$(document).ready(function() {  
         $( "#searchField" ).autocomplete({
                source: "/kb/cfcs/search.cfc?method=lookupTitle&returnformat=json",
                minLength: 3,
                select: function(event, ui) {
                    $('#searchField').val(ui.item.value);
                    $('#defaultArticleID').val(ui.item.label);
                }
            });
        });
</script>  
...
<form>
    <label for="searchField">Search field: </label>
    <input id="searchField">
    <input id="defaultArticleID">
</form> 

这篇关于JQuery自动完成远程数据(COLDFUSION)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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