jQuery 使用 AJAX 调用 ColdFusion 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/999501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:22:27  来源:igfitidea点击:

Invoke ColdFusion function using AJAX

jqueryajaxcoldfusion

提问by Arnkrishn

I need to invoke a ColdFusion function(present in a .cfm file) when the user clicks on a link. And I would like to do it using jQuery. I have a jQuery snippet which looks like-

当用户单击链接时,我需要调用 ColdFusion 函数(存在于 .cfm 文件中)。我想使用 jQuery 来做到这一点。我有一个 jQuery 片段,它看起来像 -

<script type="text/javascript">
$(document).ready(function(){
       $("td.ViewLink a").click(function(event){
         event.preventDefault();

)}

I am new to both jQuery and AJAX, so I might sound naive here. Should I use AJAX to invoke the ColdFusion function? Something like requesting to execute a specific function on the server.

我对 jQuery 和 AJAX 都不熟悉,所以我在这里听起来可能很幼稚。我应该使用 AJAX 来调用 ColdFusion 函数吗?类似于请求在服务器上执行特定功能。

Any help in this regard is appreciated.

在这方面的任何帮助表示赞赏。

Cheers.

干杯。

回答by antony.trupe

If you have multiple functions in your cfm(even if you don't), put them in a cfc. Then you can use the following url pattern to invoke a specific method.

如果您的 cfm 中有多个函数(即使您没有),请将它们放在 cfc 中。然后您可以使用以下 url 模式来调用特定方法。

cfc named myEntityWS.cfc

名为 myEntityWS.cfc 的 cfc

<cfcomponent>
  <cffunction name="updateDescription" access="remote" returntype="string">
    <cfargument name="value" type="string" required="yes">
    <cftry>
      your code here
    <cfcatch>
      <cfoutput>
        #cfcatch.Detail#<br />
        #cfcatch.Message#<br />
        #cfcatch.tagcontext[1].line#:#cfcatch.tagcontext[1].template#
      </cfoutput>
    </cfcatch>
    </cftry>
  </cffunction>
</cfcomponent>

Javascript

Javascript

$.get('myEntityWS.cfc?method=updateDescription&value=someValue');

回答by Adam Tuttle

You can't do exactly what you're trying to in your example code. You have a few options, though.

您无法在示例代码中完全按照您的意愿去做。不过,您有几个选择。

Method 1: Remotely accessible object

方法一:远程访问对象

Move your function(s) into a CFC, and access them via the URL of the CFC. This access method requires that the function use the permission attribute access='remote'-- if set to public (the default) or private, (or package, or any role levels, etc) then you'll get a method not found error when attempting to access it remotely.

将您的功能移动到 CFC 中,并通过 CFC 的 URL 访问它们。此访问方法要求函数使用权限属性access='remote'——如果设置为公共(默认)或私有(或包,或任何角色级别等),那么在尝试访问它时,您将收到方法未找到错误远程。

Doing this, you're creating a SOAP webservice and consuming it via AJAX. You do this by using the following format in your jQuery request:

这样做,您将创建一个 SOAP 网络服务并通过 AJAX 使用它。您可以通过在 jQuery 请求中使用以下格式来完成此操作:

http://domain.com/path/to/your.cfc?method=functionName&argument1=arg1Val&foo=bar&...

If you have ColdFusion 8, you can also specify the returnFormat='format'url argument, which will convert whatever native ColdFusion data objects you return to the requested format on the fly. It supports JSON, XML, and WDDX.

如果您有 ColdFusion 8,您还可以指定returnFormat='format'url 参数,它会将您返回的任何本机 ColdFusion 数据对象即时转换为请求的格式。它支持 JSON、XML 和 WDDX。

foo.cfc

文件

<cfcomponent output="false">
  <cffunction name="foobar" output="false" access="remote" hint="...">
    <cfargument name="arg1" type="string" required="true" />
    ...
    <cfreturn someVar />
  </cffunction>
</cfcomponent>

Access by URL:

通过网址访问:

http://domain.com/path/to/foo.cfc?method=foobar&arg1=some%20value&returnFormat=JSON



Method 2: Remote proxy object



方法二:远程代理对象

The negative side of approach #1 is that there is a slight efficiency hit on instantiating CFCs, so if this particular AJAX method will be run very frequently, and/or your CFC contains more than a few methods or is longer than a couple hundred lines, you don't want to instantiate it over and over for every request. Instead, you would want to look into the remote proxy pattern, where you cache the CFC that implements the functionality in Application scope, and have a separate 'remote proxy' CFC that is much lighter-weight, and simply acts as a proxy(hence the name) between the http request and the cached CFC.

方法#1 的不利方面是实例化 CFC 的效率略有下降,因此如果此特定 AJAX 方法将非常频繁地运行,和/或您的 CFC 包含多个方法或超过几百行,您不想为每个请求一遍又一遍地实例化它。相反,您需要查看远程代理模式,在其中缓存在应用程序范围内实现功能的 CFC,并拥有一个单独的“远程代理”CFC,重量轻得多,并且只是充当代理(因此名称)在 http 请求和缓存的 CFC 之间。

In this pattern, your business object (the one that has the function that does the real work) can have access=public(or package, etc), as long as the proxy has access to it. The proxy itself must have access=remote, though.

在这种模式中,您的业务对象(具有执行实际工作的功能的那个)可以拥有access=public(或包等),只要代理可以访问它。但是,代理本身必须具有access=remote

proxy.cfc

代理.cfc

<cfcomponent output="false">
  <cffunction name="foobar" output="false" access="remote" hint="...">
    <cfargument name="arg1" type="string" required="true" />
    <!--- Application.foo is an instantiated object of foo.cfc --->
    <cfreturn Application.foo.foobar(argumentCollection=arguments) />
  </cffunction>
</cfcomponent>

Access by URL:

通过网址访问:

http://domain.com/path/to/proxy.cfc?method=foobar&arg1=some%20value&returnFormat=JSON



Method 3: Do It Yourself



方法 3:自己做

Lastly, you could manually implement the function invocation and return in a CFM template. This method doesn't involve the (slight) performance hit of writing a CFC, but will be more typing for you, and additional potential points of failure. To do this, include your functions in the CFM template, and treat the output stream as just that: a stream of text that will be returned to the browser.

最后,您可以手动实现函数调用并在 CFM 模板中返回。此方法不涉及编写 CFC 的(轻微)性能损失,但会为您输入更多内容,以及其他潜在的故障点。为此,请将您的函数包含在 CFM 模板中,并将输出流视为:将返回到浏览器的文本流。

You should be careful to manage whitespace in the return value (use output=falseon function definitions, consider using <cfsetting enableCFOutputOnly='true', and just be careful about your spacing overall). If your jQuery request expects JSON back, you need to serialize it. (If you need to serialize data to JSON on ColdFusion 6 or 7, I recommend JSONUtil)

您应该小心管理返回值中的空格(output=false在函数定义上使用<cfsetting enableCFOutputOnly='true',考虑使用,并注意整体间距)。如果您的 jQuery 请求需要返回 JSON,则需要对其进行序列化。(如果您需要在 ColdFusion 6 或 7上将数据序列化为 JSON,我推荐JSONUtil

With this approach, you point your AJAX request to the .cfm file with URL parameters, and then you need to write code that takes those url parameters and passes them into the function, and then displays (essentially, returns to the AJAX request) the result of the function.

使用这种方法,您将 AJAX 请求指向带有 URL 参数的 .cfm 文件,然后您需要编写代码来获取这些 url 参数并将它们传递给函数,然后显示(本质上是返回到 AJAX 请求)函数的结果。

foo.cfm

文件

<cfsetting enableCFOutputOnly="true">
<cfparam name="arg1" default="defaultVal"/>

<cffunction name="foobar" output="false" access="remote" hint="...">
  <cfargument name="arg1" type="string" required="true" />
  ...
  <cfreturn someVar />
</cffunction>

<cfset variables.result = foobar(url.arg1) />
<cfoutput>#serializeJSON(variables.result)#</cfoutput>

回答by CFNinja

Just saw this post. I am using a cfc and jquery ajax to display bunch of calculated values. My cfc has the following:

刚看到这个帖子。我正在使用 cfc 和 jquery ajax 来显示一堆计算值。我的 cfc 有以下几点:

<cfcomponent output="true">
<cfscript>
    this.init();
</cfscript>
     <cffunction name="init" access="public" returntype="any">
       <cfset variables.dsn = application.dsn>
        <cfreturn variables.dsn> 
     </cffunction>
     <cffunction name="getFinanceTerms" access="remote" output="true" returntype="void">
         <cfargument name="sales_price" type="numeric" required="yes">
         <cfargument name="interestRate" type="numeric" required="yes">
           <!--- some calculations here --->
         #arguments.salesPrice# <!--- just to have something displayed --->
         <cfreturn>
     </cffunction>
 </cfcomponent>

I use JQuery.ajax:

我使用 JQuery.ajax:

  $.ajax({
      type:"POST",
      url:"financeTerms.cfc?method=getFinanceTerms",
      data: "sales_price=55000&interestRate=5.99",
      cache:false,
      success: function(msg) {
      $("#someDiv").html(msg);
      }
  });

Perhaps, it will be useful to somebody else...

也许,这对其他人有用......

回答by razzed

You don't necessarily need to use "AJAX" (the XML part, specifically), but you can use a remote server call:

您不一定需要使用“AJAX”(特别是 XML 部分),但您可以使用远程服务器调用:

$.get('/execute-function.cfm?func=whatever', function (result) { $('#result').html(result); });

Really depends on what you need to do with the result. The above code will place the HTML result in a div on your page:

真的取决于你需要对结果做什么。上面的代码会将 HTML 结果放在页面上的 div 中:

<div id="result"></div>

You could use an asynchronous call and parse XML, but I've found that I rarely need either.

您可以使用异步调用并解析 XML,但我发现我很少需要它们。

回答by Henry

You may try <cfajaxproxy>tag in CF8 if you like.

<cfajaxproxy>如果您愿意,可以尝试在 CF8 中标记。

回答by TRubel

Using a ColdFusion variable in JavaScript is powerful! Be sure to use

在 JavaScript 中使用 ColdFusion 变量非常强大!务必使用

<cfoutput> var #toScript(ColdFusionVAR, 'javascriptVar')# </cfoutput>

You can now reference your variable as javaScriptVarusing CFAJAXPROXY

您现在可以javaScriptVar使用 CFAJAXPROXY引用您的变量

Be sure to include this in your template

请务必将其包含在您的模板中

<head> 
<cfajaxproxy cfc="cfc.yourclassname" jsclassname="jsCFCclassName">
</head>

Using your class on the JavaScript side.

在 JavaScript 端使用你的类。

You would us it like so.

你会喜欢我们这样。

var JS_CFC_Obj;

JS_CFC_Obj = new jsCFCclassName()

You can now make calls to functions inside of that cfc.

您现在可以调用该 cfc 中的函数。

jsCFCclassName.functionName(javascript var);