$ .ajax ColdFusion cfc JSON Hello World

Phi*_*enn 1 coldfusion jquery json cfc

我尽可能地简化了这个例子.我有一个远程功能:

<cfcomponent output="false">
<cffunction name="Read" access="remote" output="false">
    <cfset var local = {}>

    <cfquery name="local.qry" datasource="myDatasource">
    SELECT PersonID,FirstName,LastName FROM Person
    </cfquery>
    <cfreturn local.qry>
</cffunction>
</cfcomponent>
Run Code Online (Sandbox Code Playgroud)

使用jQuery $ .ajax方法,我想制作一个无序的每个人列表.

    <!DOCTYPE HTML>
    <html>
    <head>
    <script src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
    google.load("jquery", "1");
    </script>
    <script type="text/javascript">
    jQuery(function($){
    $.ajax({
            url: "Remote/Person.cfc?method=Read&ReturnFormat=json",
            success: function(data){
                var str = '<ul>';
// This is where I need help:
                for (var I=0; I<data.length; I++) {
                    str += '<li>' + I + data[I][1]+ '</li>'
                }
                str += '</ul>';
                $('body').html(str);
            },
            error: function(ErrorMsg){
               console.log("Error");
            }
        });
    });
    </script>
    </head>
    <body>
    </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

我丢失的部分是我循环数据的地方.我更喜欢使用jQuery $ .ajax方法,因为我知道$ .get和$ .post没有错误捕获.

我不知道如何处理从cfc返回的JSON.

Lee*_*Lee 8

看起来结果是json格式(请查看文档http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_f_21.html)."如果指定returnformat ="json"并且函数返回一个查询,ColdFusion会将查询序列化为一个JSON对象,其中包含两个条目,列名数组和一列列数据数组.有关更多信息,请参阅SerializeJSON." http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_f_21.html

所以第一个数组(data.COLUMNS应该是一个列名数组.data.COLUMNS [0]会给你第一列的名称.data.DATA [0]会给你第一行查询.

一个很好的技巧是在chrome或firebug控制台中使用console.log(data)来查看其结构化形式的数据.

我没有测试过这个,但它应该很接近.只需从数据中生成基本表.

$.ajax({
    url: 'Remote/Person.cfc?method=Read&ReturnFormat=json',
    dataType: 'json',
    success: function(response) {
        var str = '<table><tr>';
        var i;
        var j;

        //loop over each column name for headers
        for (i = 0; i < response.COLUMNS.length; i++) {
              str += '<th>' + response.COLUMNS[i] + '</th>';
          }
        }
        str += '</tr>';

        //loop over each row
        for (i = 0; i < response.DATA.length; i++) {
          str += '<tr>';
          //loop over each column
          for (j = 0; j < response.DATA[i].length; j++) {
              str += '<td>' + response.DATA[i][j] + '</td>';
          }
          str += '</tr>';
        }
        str += '</table>';

        $('body').html(str);
    },
    error: function(ErrorMsg) {
       console.log('Error');
    }
});
Run Code Online (Sandbox Code Playgroud)