从AJAX调用返回CFC查询数据

时间:2015-03-08 22:53:33

标签: jquery ajax coldfusion cfc

我正在对CFC进行AJAX调用,以便从我的数据库中返回一条记录。记录始终以字符串形式返回。然后我用该值更新输入字段。

问题是我的字段填充了以下内容:

<wddxPacket version='1.0'><header/><data><string>0</string></data</wddxPacket>

相反,我只想要字符串的值。在此示例中:0

AJAX致电:

<script>
function populateSalesTax(){
    // Populate the start and stop odometer text boxes
    // when the selectlist ajax completes successfully

        $.ajax({
            url:'cfcs/taxdata.cfc?method=getSalesTax',
            data: { company_name: $("##company_name>option:selected").attr("Value") },
            success: function(response) {
                console.log('Sales Tax Fubction Ran Successfully');
                $("##taxRate").val( response );

                },
            error: function(response) {
                console.log('Error' + response)}
          });
    }
</script>

CFC功能:

<cffunction name="getSalesTax" access="remote" returnType="string">
   <cfargument name="company_name" type="any" required="true">

   <!--- localize function variables --->
   <cfset var taxDetail = "">
   <cfoutput>
   <cfquery name="taxDetail" datasource="#datasource#">
       SELECT tax_rate
       FROM   customer_table
       <!--- adjust cfsqltype if needed --->
       WHERE company_name = <cfqueryparam value="#ARGUMENTS.company_name#"
                                cfsqltype="cf_sql_varchar">
   </cfquery>
   </cfoutput>

   <cfreturn taxDetail.tax_rate>
</cffunction>

输入字段:

<cfinput name="taxRate" id="taxRate" type="text" size="2" readonly="yes">

2 个答案:

答案 0 :(得分:1)

我这里有很多代码,因为我做的事情与大多数情况有很大不同,但这是一个进化。 以下是我创建典型表的方法:

if exists (select * from sysobjects where id = object_id(N'myTable') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE myTable
GO
CREATE TABLE myTable(
myTableID Int Identity(1000,1) PRIMARY KEY NONCLUSTERED
,myTableName varchar(128) default ''
,myTableDesc varchar(max) default ''
,myTableSort Int default 0
)
GO
INSERT INTO myTable(myTableName,myTableSort) VALUES('One',1)
INSERT INTO myTable(myTableName,myTableSort) VALUES('Two',2)
INSERT INTO myTable(myTableName,myTableSort) VALUES('Three',3)

我使用存储过程。这是SQL代码:

create schema myTable authorization dbo
-- It might seem odd to create a schema called with the name of the table, but that's how I organize the stored procedures by table name.
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'myTable.[get]') AND type in (N'P', N'PC'))
DROP PROC myTable.[get]
GO
CREATE PROC myTable.[get]
(@UsrID Int
,@RemoteAddr Varchar(15)
,@myTableID Int
) AS
SELECT myTableID,myTableName,myTableDesc,myTableSort
FROM myTable
WHERE myTableID = @myTableID
GO
exec myTable.[get] 0,'',1001

@UsrID是每个存储过程中的第一个参数。这是谁想知道的。

@RemoteAddr是每个存储过程中的第二个参数。这是用户的IP地址。 现在,我知道这不是万无一失的,但这里的想法是安全就是这样 1)@UsrID是他们所知道的(他们必须知道以用户身份登录的密码)。

2)@RemoteAddr是他们拥有的东西(虽然IP地址可以被欺骗)。

@myTableID是@myTable的主键。我总是将主键命名为表名,后跟ID。

这是一个典型的.cfm页面:

<cfscript>

</cfscript>

<cfoutput>
<cfinclude template="/Inc/html.cfm">
<link rel="stylesheet" type="text/css" href="Index.css">
<cfinclude template="/Inc/body.cfm">
<ul>
    <li><a class="myClass" data-mytableid="1000" href="JavaScript:;">Click One!</a></li>
    <li><a class="myClass" data-mytableid="1001" href="JavaScript:;">Click Two!</a></li>
    <li><a class="myClass" data-mytableid="1002" href="JavaScript:;">Click Three!</a></li>
</ul>
<cfinclude template="/Inc/foot.cfm">
<script src="Index.js"></script>
<cfinclude template="/Inc/End.cfm">
</cfoutput>

我在所有网页中都包含的脚本:

window.dom = {}
dom.msg = $('#msg')
dom.main = $('main')
dom.fail = function(xhr, status, response) {
    dom.msg.text(status + ': ' + response).addClass('label-warning')
    dom.main.html(xhr.responseText)
    debugger
}

页面本身的脚本:

(function() {
    $(document).on('click','.myClass',clicked)

    function clicked() {
        var local = {}
        local.url = 'myTable.cfc'
        local.type = 'POST' // or GET
        local.dataType = 'json'
        local.data = {}
        local.data.method = 'get';
        local.data.myTableID = $(this).data('mytableid')
        local.context = this;
        result = $.ajax(local)
        result.fail(dom.fail)
        result.done(done)
    }
    function done(response, status, xhr) {
//      console.log(response.COLUMNS)
//      console.log(response.DATA)
//      console.log(response.DATA[0])
//      console.log(response.DATA[0][0]) // myTableID
//      console.log(response.DATA[0][1]) // myTableName
//      console.log(response.DATA[0][2]) // myTableDesc
//      console.log(response.DATA[0][3]) // myTableSort
//      console.log(status)
//      console.log(xhr)
    }
})()

最后,myTable.cfc:

component {

remote function get(myTableID) returnformat='json' {
    storedproc dataSource=session.dataSource
        procedure='myTable.[get]' {
        procparam cfSqlType='cf_sql_integer' value=session.Usr.UsrID;
        procparam cfSqlType='cf_sql_varchar' value=session.RemoteAddr;
        procparam cfSqlType='cf_sql_integer' value=arguments.myTableID;
        procresult resultset=1 name='result';
    }
    return result
}
}

我应该粘贴一个缩写的Application.cfc:

component {
this.Name = 'myAJAX'
this.dataSource = 'LR2015Summer1'
this.SessionManagement = true

function onSessionStart() {
    session.dataSource = this.dataSource
    session.RemoteAddr = getPageContext().getRequest().getRemoteAddr()
    session.Usr = {}
    session.Usr.UsrID = 0
}

function onRequestStart(LogCFCName) {
    setting showDebugOutput=false;
    if (isDefined('url.onSessionStart')) {
        onSessionStart()
    }
    request.msg = ''
    request.mod = 'label-info'

    request.title='How I AJAX and return a query'
    request.home = '/HowIWrite/AJAX/cfc'
    request.css       = url.css       ?: true
    request.js        = url.js        ?: true
    request.bootstrap = url.bootstrap ?: true
    request.bootstrap_theme = 'bootstrap-theme'
    request.tryCatch  = url.tryCatch  ?: false
    request.navbar    = url.navbar    ?: true
    request.container = url.container ?: true
    request.GoogleMaterialdesign = url.GoogleMaterialdesign ?: true
    request.jQueryUI  = url.jQueryUI  ?: false
    request.jQueryUI_theme = 'ui-lightness' // black-tie,blitzer,cupertino,dark-hive,dot-luv,eggplant,excite-bike,flick,hot-sneaks,humanity,le-frog,mint-choc,overcast,pepper-grinder,redmond,smoothness,south-street,start,sunny,swanky-purse,trontastic,ui-darkness,ui-lightness,vader

    request.cgiName = getPageContext().getRequest().getServletPath()
    request.cgiName = Left(request.cgiName,Len(request.cgiName)-4)
    request.cgiName = ListLast(request.cgiName,'/')
    request.cssName = request.cgiName & '.css'
    request.jsName  = request.cgiName & '.js'
}

}

答案 1 :(得分:1)

您可以修改您的CFC:

<cfset response = { taxRate = taxDetail.tax_rate } />
<cfreturn serializeJSON(response)>

(ajax成功方法应该有response.TAXRATE

或您的ajax调用网址:

cfcs/taxdata.cfc?method=getSalesTax&ReturnFormat=json

<强> 但是

从你在ajax请求url:'cfcs/taxdata.cfc?method=getSalesTax'中的相对路径判断我可以安全地假设你正在尝试在同一个来源(同一站点)上执行ajax请求而你实际上并不需要 / em> remote方法,但publicpackage方法。

您应该了解声明方法remote时出现的安全问题。如果没有正确的安全层或role已定义,您已打开任何人使用的方法,包括恶意用户。

所以你应该拥有的是:

  • CFC前面的另一个抽象层 - 至少只是一个实例化对象并调用getSalesTax的cfm,但理想情况下是一个框架
  • 访问publicpackage而非remote
  • 在抽象层上声明的适当内容类型,它返回税率响应对象(例如<cfcontent type="application/json" reset="true" />