How to call cffunction on the cfm page from javascript?

瘦欲@ 提交于 2021-02-07 09:44:09

问题


I was wondering if I can call cffunction on my cfm page? I have onClick button that should make a call to the cffunction that is on the same page. Also I have tried to put cfcomponent around my function but I was getting this error:

Invalid CFML construct found on line 94 at column 1.
ColdFusion was looking at the following text:

<
The CFML compiler was processing:
< marks the beginning of a ColdFusion tag.Did you mean LT or LTE?

So far I have this:

<cffunction name="getRecords" access="remote">
    <script>
        alert('test');
    </script>
</cffunction>

here is my JS Function:

function getRecs(){
    try{
        location.href = 'myCFMpage.cfm?method=getRecords';
    }catch(err){
        alert('Error')
    }   
}

I'm not sure if this even possible, my current code did not trigger alert in cffunction. Reason why I'm trying to do this because I have a cfquery on this page and I want to grab the data from that query when user click on the button and then to do some manipulation. If anyone can tell me if this is possible or is there any better way to approach this problem please let me know.


回答1:


In the past, I've used cfajaxproxy to accomplish calling functions from a component (cfc) to javascript. (I don't do this any more because of different development paradigm, but this might be helpful to get you going.) First, create a cfc with your functions.

<cfcomponent>
    <cffunction name="getRecords" access="remote" returntype="string">
        <cfquery name="someQuery" datasource="someDataSource">
            select * from records
        </cfquery>
        <cfreturn serializeJSON(someQuery,'struct')> 
    </cffunction>
</cfcomponent>

In your template, .cfm file, you would use cfajaxproxy to declare the component for us in your javascript.

<cfajaxproxy cfc="yourComponent" jsclassname="jsClass">

Then, in the same template, in your javascript you would do the following and you will be able to use the cfc functions as methods from the jsClass.

<script type="text/javascript">
    var _myFuncs = new jsClass()

    function buttonClicked() {
        var _records = JSON.parse(_myFuncs.getRecords());
    }

</script> 

Hopefully, this provides some insight. There are many solutions out there, this being one. My current development pattern is to use Angular and do $http calls to CF components. And I roll my own JSON in the cffunctions. But this is how I started out with just plain JS and CF.



来源:https://stackoverflow.com/questions/40406253/how-to-call-cffunction-on-the-cfm-page-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!