ColdFusion cfmproxy. cfm code:
/*** @ Hint returns the request object submitted by Ajax * @ returntype any */function getajaxrequest () {var content = getrequestcontent (); if (content = "" & isdefined ("URL. P ") {content = URL. p;} If (isjson (content) {return deserializejson (content) ;}else {return "";}}
/*** @ Hint returned page request content * @ returntype string */function getrequestcontent () {var result = ""; var httprequest = getpagecontext (). getrequest (); var contentlength = httprequest. getcontentlength (); If (contentlength GT 0) {bytearray = getbytearray (contentlength); httprequest. getinputstream (). readline (bytearray, 0, contentlength); Result = tostring (Createobject ("Java", "Java. lang. string "). init (bytearray);} return result ;}
<cfprocessingdirective pageencoding="utf-8" />
<Cftry> <cfscript> cfmresult ={}; cfmresult. success = false; cfminfo = $ utils. getajaxrequest (); </cfscript> <cfif isstruct (cfminfo) and structkeyexists (cfminfo, "cfmpage") and structkeyexists (cfminfo, "method")> <cfinclude template = "# cfminfo. cfmpage # "/> <cfscript> If (structkeyexists (variables, cfminfo. method) {method = Variables [cfminfo. method]; If (isdefined ("cfminfo. arguments ") {cfmresult. data = method (argumentcollection = cfminfo. arguments);} else {cfmresult. data = method ();} cfmresult. success = true;} else {cfmresult. data = "the requested method does not exist" ;}</cfscript> <cfelse> <cfset cfmresult. data = "request format error"> </cfif> <cfcatch type = "any"> <cfset cfmresult. data = cfcatch. message/> <cfif _ $ returnexceptiondetail {1} gt; <cfset cfmresult. exception = cfcatch> </cfif> </cfcatch> </cftry> <cfcontent type = "application/JSON; charset = UTF-8"/> <cfoutput> # serializejson (cfmresult) # </cfoutput>
Client jquery code:
_postCFProxy: function (request) { var dtd = jQuery.Deferred(); jQuery.ajax({ type: "POST", url: request.url, contentType: "application/json", data: jQuery.toJSON(request) }) .done(function (data, textStatus, jqXHR) { if (data.SUCCESS) { dtd.resolve(data.DATA); } else { dtd.reject(data); } }) .fail(function (jqXHR, textStatus, errorThrown) { dtd.reject({ DATA: jqXHR.responseText }, jqXHR); }); return dtd.promise(); }, _callcfm: function (cfm, method, params) { var cfminfo = { url: "cfmproxy.cfm", cfmpage: cfm, method: method }; if (params) { cfminfo.arguments = params; } return this._postCFProxy(cfminfo); }