【问题标题】:Is there a way to send json to a remote cfc using XMLHttpRequest()?有没有办法使用 XMLHttpRequest() 将 json 发送到远程 cfc?
【发布时间】:2013-10-22 16:41:03
【问题描述】:

我已经尝试了很多不同的选项来在不使用 jquery 的情况下将 json 数据发送到 cfc,我的问题是如何使用 XMLHttpRequest() 而不是 $.ajax 来完成?它将请求发送到 CFC,但我无法将任何变量传递给它一直说“FORMDATA”(这是我的未传入)的 cfc,我有一个名为表单数据的变量。我能够让它工作的唯一方法是使用新的 formData() 对象,但我需要它在 IE 8 和 9 中工作?

  <cfcomponent>

    <cffunction name="validate" access="remote" >

        <cfargument name="formdata" required="true" type="string"/>

        <!--- <cfif isJSON(arguments.formdata)>
            <cfset values = deserializeJSON(arguments.formdata)>
        </cfif> --->
        <cfdump var="#variables#">
        <cfdump var="#arguments#">

        <cfreturn { STATUS = 200, MESSAGE = "data recieved"}>

    </cffunction>

</cfcomponent>

这是我的 javascript

         var xhr = new XMLHttpRequest();
         xhr.open("POST", "validation.cfc?method=validate", true);
         xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

          // send the collected data as JSON
         xhr.send(JSON.stringify({formdata:data}));

         xhr.onloadend = function () {
            console.log(xhr.responseText);
         };

我不确定我做错了什么?

【问题讨论】:

  • 标题不反映您的实际问题。
  • 抱歉我改写了标题

标签: javascript ajax json coldfusion


【解决方案1】:

您需要发送表单编码数据,使其位于FORM 范围内(在远程调用 CFC 函数的情况下为arguments)。所以将内容类型更改为:

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

并将 send() 调用更改为:

xhr.send("formdata=" + JSON.stringify(data));

它应该以 JSON 字符串的形式传递给 arguments.formdata 参数。

【讨论】:

  • 这是一个很好的方法谢谢你我实际上也用 angular js 做到了
  • 哈哈好吧,你说没有 jquery,所以我认为你的意思是没有任何类型的库,因为某种原因你仅限于纯 ol'js。 :)
【解决方案2】:
        var params = "method=validate&returnformat=json";
        params += "&formdata=" + json;

        $http({
               method: 'POST', 
               url: 'validation.cfc', 
               data:params, 
               headers: {"Content-type":"application/x-www-form-urlencoded"}
        }).success(function(data){

            console.log(data);

        })

【讨论】:

    猜你喜欢
    • 2011-05-21
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    相关资源
    最近更新 更多