2012-05-06 18 views
2

次のコードが機能します。私がしたいのは、単一の値を受け入れることから、オブジェクトの配列を受け入れることに変更することです.1、 "Item One"をポストするのではなく、オブジェクトをループして1、 "Item One" 2、 "2つ目の項目" などAjax経由で複数の行を投稿する方法

!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

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でループするだけです。

+0

これはそれですか?それは簡単すぎるようです!私は今試してみよう! –

+0

私は次のようになります: "NetworkError:500要素DATAARRAYは引数に未定義です - http://www.phillipsenn.com/Matrix/JSON/Paul/add.cfc?method=addData&returnFormat=json" –

+0

JSON.stringifyを文字列として渡しますが、その後、cfcで文字列を分割する必要があります。それはあまりにも悪くないかもしれない。 –