来自 AJAX 请求的发布参数在 ColdFusion 的表单范围

Post parameters from AJAX request undefined in form scope in ColdFusion(来自 AJAX 请求的发布参数在 ColdFusion 的表单范围内未定义)

本文介绍了来自 AJAX 请求的发布参数在 ColdFusion 的表单范围内未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 ColdFusion 8 培训应用程序,我在其中发出一些 AJAX 请求(没有任何库,例如 jQuery)来支持一个非常基本的 CRUD 应用程序.高级架构包括一个 CFM 视图、一个具有远程访问方法的 CFC,它接收 AJAX 请求,以及一个充当模型并具有所有数据库查询的 CFC.对于仅检索不需要任何类型的绑定变量的数据(例如从表中获取所有行),AJAX 查询工作正常.但是,当我尝试将任何内容发布到 CFC 中间层时,我收到有关我正在寻找的值在 Form 范围内未定义的错误(据我所知,这是存储后参数的位置).我什至用 Tamper Data 剖析了请求,并验证了 post 参数的名称和值是否符合我的预期.

I am working on a ColdFusion 8 training application where I'm making some AJAX requests (without any libraries such as jQuery) to support a very basic CRUD application. The high level architecture includes a CFM view, a CFC with remote access methods which receive the AJAX requests, and a CFC which acts as a model and has all of the database queries. For just retrieving data that doesn't require any sort of bind variables (like getting all rows from the table), the AJAX queries are working fine. When I try to post anything to the CFC middle layer, however, I'm getting errors about the values I'm looking for being undefined in the Form scope (which from my understanding is where post parameters will be stored). I even dissected the requests with Tamper Data and verified that the names and values of the post parameters are as I expect them to be.

以下是 JS AJAX 请求的示例:

Here is an example of the JS AJAX requests:

    function addLocation(locToAdd) {
            var thisAccess = new AccessStruct("POST", "jsontest.cfc?method=addNewLocation", getLocations, "newLoc=" + JSON.stringify(locToAdd));
            accessWrapper("addLoc", thisAccess);

    function accessWrapper(action, accessDef) {
            var ajaxRequest = new XMLHttpRequest();
            var nextStep;
            if (action != "getLocs") {
                nextStep = getLocations;
            } else {
                nextStep = buildTable;
            }

            ajaxRequest.onreadystatechange = function() { // using a closure so that the callback can
                if (ajaxRequest.readyState == 4) {        //   examine the request and nextStep
                    if (ajaxRequest.status == 200) {
                        if (nextStep != null) {
                            nextStep(ajaxRequest);
                        }
                        return true;
                    } else {
                        alert("Request Could Not Be Completed; Errors On Page");
                        return false;
                    }
                }
            }
            ajaxRequest.open(accessDef.method, accessDef.url, true);
            ajaxRequest.send("newLoc=" + accessDef.params);
    }


    function Loc(locCode, parLocCode, name, addrL1, addrL2,
                            city, stateProv, postal, locTypeCode) {
            this.locCode     = locCode;
            this.parLocCode  = parLocCode;
            this.name        = name;
            this.addrL1      = addrL1;
            this.addrL2      = addrL2;
            this.city        = city;
            this.stateProv   = stateProv;
            this.postal      = postal;
            this.locTypeCode = locTypeCode;
        }

        function AccessStruct(method, url, nextStep, params) {
            this.method   = method;
            this.url      = url;
            this.nextStep = nextStep;
            this.params   = params;
        }

基本上页面上发生的事情是正在为用户"呈现由所有位置 (loc) 记录填充的表.有一个添加新用户的表单,当他们单击添加按钮时,会创建一个 Loc 结构,其中包含他们输入的信息并传递给 addLocation 函数.这将创建一个 Access 结构,其中将包括请求 URL、方法、用作回调的函数的名称以及任何 post 参数.这些都被传递到 accessWrapper 函数中,该函数将创建 XMLHttpRequest 并处理 AJAX 请求.我为 onreadystatechange 回调函数使用了一个闭包,以便它可以知道 XMLHttpRequest 对象和 Access 结构中定义的回调函数(该回调函数通常用于在添加、删除记录后刷新视图表,或编辑).

Essentially what's happening on the page is that a table populated by all the location (loc) records is being rendered for a "user". There is a form to add a new user, and when they click the add button, a Loc structure is created containing the information they entered and is passed to the addLocation function. This creates an Access structure, which will include the request URL, method, the name of a function to act as a callback, and any post parameters. This is all passed into the accessWrapper function, which will create the XMLHttpRequest and process the AJAX request. I used a closure for the onreadystatechange callback function so that it could be aware of the XMLHttpRequest object and the callback function defined in the Access structure (this callback function will be generally be used to refresh the view table after a record is added, deleted, or edited).

这是报告问题的中间层 CFC 中的 cffunction.我不会费心发布 DAO CFC,因为它已经在其他地方进行了测试,并且在此过程中甚至没有达到(因为它在中间 [或控制器] 级别失败)

Here is the cffunction within the middle-layer CFC where the problem is being reported from. I won't bother to post the DAO CFC as that has been tested elsewhere and is not even being reached during this process (because it's failing at the middle [or controller] level)

 <cffunction name="addNewLocation" output="false" access="remote">
    <cfset var deserializedLocation = "">
    <cfscript>
        deserializedLocation = DeserializeJSON(Form.newLoc);
    </cfscript> 
    <cfobject component="locationDAO" name="locationDAOObj">
    <cfinvoke
        component="#locationDAOObj#"
        method="addLocation">
        <cfinvokeargument name="code" value="#deserializedLocation.locCode#">
        <cfinvokeargument name="parentCode" value="#deserializedLocation.parLocCode#">
        <cfinvokeargument name="name" value="#deserializedLocation.name#">
        <cfinvokeargument name="addr1" value="#deserializedLocation.addrL1#">
        <cfinvokeargument name="addr2" value="#deserializedLocation.addrL2#">
        <cfinvokeargument name="city" value="#deserializedLocation.city#">
        <cfinvokeargument name="stateProv" value="#deserializedLocation.stateProv#">
        <cfinvokeargument name="postal" value="#deserializedLocation.postal#">
        <cfinvokeargument name="locationType" value="#deserializedLocation.locTypeCode#">
    </cfinvoke>
</cffunction>

请求响应中的错误是:500 元素 NEWLOC 在 FORM 中未定义

The error in the request response is: 500 Element NEWLOC is undefined in FORM

就像我之前说的,我在 Tamper Data 中检查了请求,那里看起来不错.提前感谢各位大佬可能提供的任何帮助!

Like I said before, I've checked the request in Tamper Data, and it looks fine there. Thanks in advance for any help you great folks might be able to offer!

推荐答案

当您将 Ajax 发布到 CFC 时,绝对有一个 FORM 范围.

There absolutely is a FORM scope when you do an Ajax post to a CFC.

本示例通过 Ajax 将表单数据 POST 到 CFC 函数不带参数,并返回 FORM 范围的 JSON 格式.是的,你应该有参数来记录,指定需要/不需要和数据类型,但它们不是强制性的.

This example POSTs form data via Ajax to a CFC function with no arguments and returns the JSON format of the FORM scope. Yes, you should have arguments to document, specify required/not required and data type, but they're not mandatory.

你有什么理由不使用 jQuery 吗?它可能会让你的生活更轻松.

Is there any reason you aren't using jQuery? It would probably make your life much easier.

您将表单数据发送到 Ajax 调用的方式一定有问题.如果您使用 FireBug 观察您的 Ajax 调用,您可以看到 POSTed 参数.

There must be something wrong with how you're sending the form data to the Ajax call. If you use FireBug to watch your Ajax calls, you can see the POSTed parameters.

HTML

<html>
    <head>
        <title>Ajax POST to CFC</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript" src="test.js">
    </head>
    <body>

        <form id="foo" action="" method="post">

            <input type="text" id="a" name="a" value="Hello" />
            <br />
            <input type="text" id="b" name="b" value="Goodbye" />
            <br />

            <textarea id="data" cols="30" rows="10" disabled="true"></textarea>
            <br />
            <input type="button" id="btnSubmit" value="Do Ajax!" />

        </form>

    </body>

</html>

JavaScript

$(document).ready(function() {
    $('#btnSubmit').on('click', function() {
        $.ajax({
            asynch : true,
            type : 'POST',
            dataType : 'json',
            url : 'test.cfc?method=testing&returnformat=json',
            data : {
                a : $('#a').val(),
                b : $('#b').val()
            },
            success : function(data, textStatus) {
                $('#data').val(JSON.stringify(data));
            }
        });
    });
});

CFC

<cfcomponent>
    <cffunction name="testing" access="remote" output="false" returntype="string">
        <cfreturn serializeJSON( form ) />
    </cffunction>> 
</cfcomponent>

老派,没有 jQuery,只有普通的 JavaScript

我在这里找到了一个没有 jQuery 的 Ajax POST 的简单示例:http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

I found a simple example of an Ajax POST without jQuery here: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

HTML
删除 jQuery SCRIPT 标记,将另一个 SCRIPT 更改为 test-nojq.js 并更改提交按钮以添加 onclick 事件.

HTML
Remove the jQuery SCRIPT tag, change the other SCRIPT to test-nojq.js and change the submit button to add an onclick event.

<input type="button" id="btnSubmit" value="Do Ajax!" onclick="doSubmit();" />

JavaScript:test-nojq.js

function doSubmit(){
    var http = new XMLHttpRequest();
    var url = "test.cfc";
    var params = "method=testing&returnformat=json";
        params += "&a=" + document.getElementById('a').value;
        params += "&b=" + document.getElementById('b').value;
    http.open("POST", url, true);
    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", params.length);
    http.setRequestHeader("Connection", "close");
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            document.getElementById('data').value = http.responseText;
        }
    }
    http.send(params);
}

这篇关于来自 AJAX 请求的发布参数在 ColdFusion 的表单范围内未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:来自 AJAX 请求的发布参数在 ColdFusion 的表单范围

基础教程推荐