2012-05-06 75 views
2

下面的代碼工作後多行。我想要做的是從接受一個值,以接受對象的數組改變,從而代替發佈1,「項目一」,我通過循環的對象和發佈1,「項目一」 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中拆分字符串。這可能不算太壞。 –