如何通过Ajax发布多行

时间:2012-05-06 00:59:40

标签: ajax coldfusion

以下代码有效。我想要做的是将它从接受单个值更改为接受一个对象数组,这样我不是发布1,“Item One”,而是循环遍历该对象并发布1,“Item One”, 2,“第二项”等。

!function($, window, undefined) {
    var local = {};
    local.data = {};
    local.type= 'post',
        local.dataType= 'json',
        local.data.method = 'Save',
        local.data.ItemNo = 1;
        local.data.ItemName = 'Item One';

    var myPromise = $.ajax('Upload.cfc',local);
    myPromise.done(function(result) {
        console.log('success!');
    });

    myPromise.fail(function(A,B,C) {
        $('body').append(A.responseText);
        console.log(B);
        console.log(C);
    });
}(jQuery, window);

<cfcomponent>
<cffunction name="Save" access="remote">
    <cfargument name="ItemNo">
    <cfargument name="ItemName">
    <cfset var local = {}>

    <cfquery datasource="#Application.Datasource#" username="#Application.Username#" password="#Application.Password#">
    INSERT INTO lru.Item(ItemNo,ItemName) VALUES
    (<cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.ItemNo#">
    ,<cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.ItemName#" maxlength="10">
    )
    </cfquery>
</cffunction>
</cfcomponent>

1 个答案:

答案 0 :(得分:1)

index.cfm:

  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        $('#save').click(function(){
          $.ajax({
            url: 'add.cfc?method=addData&returnFormat=json',
            type: "post",
            data: { dataArray: [$('#test1').val(),$('#test2').val(),$('#test3').val() ] },
            dataType: 'json',
            success: function(data){
              $('#result').html(data);
            }
          });
        });
      });
    </script>
  </head>
  <body>
    <form name="sub" method="post">
        Test1: <input type="text" name="test1" id="test1" /><br />
        Test2: <input type="text" name="test2" id="test2" /><br />
        Test3: <input type="text" name="test3" id="test3" /><br />
        <button type="button" id="save" name="save">Save</button>
    </form>

    <div id="result" />

  </body>

add.cfc:

<cfcomponent>
    <cffunction name="addData" access="remote" returntype="string" >
        <cfargument name="dataArray" type="array" />

        <cfset var result = "" />

        <cfloop array="#arguments.dataArray#" index="i" >
            <cfset result = result & "R: " & i & ", " />
        </cfloop>

        <cfreturn result />

    </cffunction>
</cfcomponent>

这个例子应该让你前进,只需将一个数组从javascript传递给ColdFusion,然后在你的cfc中循环该数组。