$.ajax ColdFusion cfc JSON Hello World

发布于 2024-08-27 11:05:22 字数 1490 浏览 9 评论 0原文

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

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

并使用 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>

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

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

I've simplified this example as much as I can. I have a remote function:

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

And using the jQuery $.ajax method, I would like to make an unordered list of everyone.

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

The part where I'm lost is where I'm looping over the data.
I prefer to the use jQuery $.ajax method because I understand that $.get and $.post don't have error trapping.

I don't know how to handle JSON returned from the cfc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

阳光的暖冬 2024-09-03 11:05:22

看起来结果是 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');
    }
});

Looks like the result is in json format(check the docs http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_f_21.html).
"If you specify returnformat="json" and the function returns a query, ColdFusion serializes the query into a JSON Object with two entries, and array of column names, and an array of column data arrays. For more information see SerializeJSON." http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_f_21.html

So the first array(data.COLUMNS should be an array of column names. data.COLUMNS[0] would give you the name of the first column. data.DATA[0] would give you the first row of the query.

A nice trick is to use console.log(data) in chrome or firebug console to view the data in it's structured form.

I didn't test this, but it should be close. Just generating a basic table from the 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');
    }
});
<逆流佳人身旁 2024-09-03 11:05:22

最简单的方法是直观地查看返回的 JSON 数据的结构。那么横穿 JS 对象应该不会太难。您尝试过 JSON 可视化吗? http://chris.photobooks.com/json/default.htm

如果您需要的是 PersonID,您也可以从 CF 返回 PersonID 的数组或列表。

或者,您可以选择要求 CF 返回纯文本,并生成所有

  • 。通过 ajax 传递的消息会更大,但需要维护的 JS 代码会更少。 CFML 更容易维护,对吗? :)
  • The easiest way would be to visually see how the returned JSON data is structured. Then it shouldn't be too hard to transverse the JS object. Have you tried JSON Visualization? http://chris.photobooks.com/json/default.htm

    If all you need is the PersonID, you can return array or list of PersonID from CF as well.

    Or optionally, you can ask CF to return Plain text, with all the <li>'s generated. The message passed through ajax will be larger, but you'll have less JS code to maintain. CFML is easier to maintain, right? :)

    回忆凄美了谁 2024-09-03 11:05:22

    我对 ColdFusion 不太熟悉,但是您尝试过将数据类型设置为 JSON 吗?

    $.ajax({
        url: 'Remote/Person.cfc?method=Read&ReturnFormat=json',
        dataType: 'json',
        success: function(response) {
            var data = response.DATA;
            var str = '<ul>';
    
            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');
        }
    });
    

    如果您返回的数据类似于以下内容,那么这应该可行:

    [["PersonID1", "FirstName1", "LastName1"],["PeronID2", "FirstName2", "LastName2"]] .. etc
    

    如果上述方法不起作用,如果您可以显示请求返回的原始 JSON 数据,我应该能够轻松修复它。

    另外,不确定它是否在您的代码中,但您在 for 循环中的行末尾错过了一个分号。

    I'm not very familiar with ColdFusion but have you tried setting the data type to JSON?

    $.ajax({
        url: 'Remote/Person.cfc?method=Read&ReturnFormat=json',
        dataType: 'json',
        success: function(response) {
            var data = response.DATA;
            var str = '<ul>';
    
            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');
        }
    });
    

    That should work if the data you're getting back resembles something like:

    [["PersonID1", "FirstName1", "LastName1"],["PeronID2", "FirstName2", "LastName2"]] .. etc
    

    If the above doesn't work if you could show the raw JSON data being returned by your request I should be able to easily fix it.

    Also, not sure if it was in your code, but you missed a semi-colon at the end of the line in the for loop.

    荒路情人 2024-09-03 11:05:22

    选项:

    在你的情况下,我会输入

    <cffunction name="keywordAutoComplete" access="remote" 
                returntype="struct" returnformat="JSON" >
    

    BUT

    这与 returntype="string" returnformat="plain" + 的作用相同
    从 jQuery 的角度来看,这是一个问题,因为即使您使用按列进行序列化,也会得到丑陋的 JSON。

    1. 您可以通过 cfloop 和连接手动创建 JSON 字符串:/
    2. 使用 cfjson.cfc 覆盖serializeJSON
    3. 转到 Ben Nadel 的站点并采用他的 toJSON 方法并以某种方式修改它以满足您的需求

    其他东西是serializeJSON,返回大写的键,所以要注意,使用lcase()或者在js中编写.LIKETHIS。

    PS:尝试在 jQuery 中动态创建 html:

    var someLiElement = $('<li />').addClass('custom_class')
                     .text('Foo bar')
                     .attr('id', 'custom_id' + someInteger)
    

    然后将方法附加到父元素

    Options :

    In your case I'd put

    <cffunction name="keywordAutoComplete" access="remote" 
                returntype="struct" returnformat="JSON" >
    

    BUT

    this does the same thing as returntype="string" returnformat="plain" + <cfreturn serializeJSON(query) >
    and that's a problem form jQuery point of view because you get ugly JSON even if you use serializeJSON srerialization by columns.

    1. You can make JSON string manually through cfloop and concatenation :/
    2. Use cfjson.cfc which overrides serializeJSON
    3. Go to Ben Nadel's site and take his toJSON method and modify it somehow to fit your needs

    Other thing is serializeJSON, returns uppercased keys, so pay attention, use lcase() or write .LIKETHIS in js.

    PS: Try this for dynamic creaiton of html in jQuery:

    var someLiElement = $('<li />').addClass('custom_class')
                     .text('Foo bar')
                     .attr('id', 'custom_id' + someInteger)
    

    then append method to parent element

    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文