2010-01-09 92 views
1

如何使用jQuery.post()将表单发布到Coldfusion.cfc方法并返回json数据?是否有某种方法需要格式化url或表单值以指定cfc方法来远程调用?我如何告诉Coldfusion返回json数据?如何使用jQuery.post()将ColdFusion 8 cfc返回JSON数据?

我搜索了现有的jQuery/Coldfusion.cfc问题,我正在寻找一些清晰的。我找不到一个能够显示Coldfusion cfc完整过程的例子。

HTML表单:

<!--- Assume: jquery, jquery-ui, sample.js is loaded ---> 
<p><a href="#" id="openDialog">Open Dialog</a></p> 

<div id="myDialog" title="My Dialog" class="dialog"> 
<form id="myForm"> 
    <label for="title">Title:</label><br /> 
    <input type="text" name="title" id="title" value="" /><br /> 
    <label for="address">Address:</label><br /> 
    <input type="text" name="address" id="address" value="" /><br /> 
    <input type="submit" name="save" value="save" /> 
</form> 
</div> 

sample.js:

jQuery(function ($) { 

    var saveUrl = "remote.cfc?method=save"; // Is this the right way?? 

    // Bind link to open the dialog box 
    $('a#openDialog').click(function() { 
     $('#myDialog').dialog('open'); 
    }); 

    // Configure jQuery UI dialog box and callback methods 
    // Is this right?? 
    $("#myForm").dialog({ 
     buttons: { 
      'Save': function() { 
       $.post(saveUrl, $("#myForm").serialize(), function(result){ 
        alert("Result: " + result); 
        }, "json"); 
       $(this).dialog('close'); 
       }, 
      'Cancel': function() { 
       $(this).dialog('close'); 
      } 
    }); 
}); 

remote.cfc:

<cfcomponent> 

    <!--- If I set the returnFormat to JSON do I need to specify json in the post too? ---> 
    <cffunction name="save" access="remote" returntype="string" returnFormat="JSON"> 
     <cfargument name="title" type="string" required="yes"> 
     <cfargument name="address" type="string" required="yes"> 
     <cfset var result = structNew()> 

     <!--- Do some data manipulation or cfquery here, save to result struct ---> 

     <cfreturn result> 
    </cffunction> 

</cfcomponent> 

*注意,我发现有ColdFusion的调试真的会偷懒up cfc返回值,所以它应该被抑制或关闭。

+0

您可以在帖子中传递returnformat,而不是将其设置为cffunction标记中的属性。 您可能想要在cfcomponent和cffunction标记中将输出设置为false。 – 2010-01-09 20:13:50

回答

1

你有什么看起来不错,在那里它遇到错误的,什么是错误?如果没有明显的错误消息,我会做的第一件事就是在远程方法中抛出一条日志语句,并确定您是否正在调用服务器。如果这是真的,并且它一直到最后,那么就会提醒回到回调的对象(看起来您已经这么做了)。

要回答你的具体问题,remote.fc?method=methodName是正确的URL,如果你发布的数据,应该有标题等,所以你应该没问题。如果您收到一个错误或者最终警报的价值是什么,请回复错误。

+0

很好的建议。使用Coldfusion进行AJAX调试需要一些不同于我所采用的策略。 – 2010-01-14 20:28:43

1

如果将returnFormat设置为JSON,则不需要在帖子中指定json。为了向后兼容的原因,默认情况下为returnformat = WDDX。

如果您想要易用,请查看<cfajaxproxy>和各种cf-ajax UI组件标签。

退房此相关的问题:Invoke ColdFusion function using AJAX