【问题标题】:How can we pass the JSON data in http request body in form post我们如何在表单 post 中传递 http 请求正文中的 JSON 数据
【发布时间】:2018-10-15 15:32:44
【问题描述】:

我们有一个将数据提交到新标签页的表单。喜欢,

<form name='formOne' action='/action.cfm' method='post' target='_blank'>
    <input type='hidden' name='employee' value='{"first_name": "test","last_name":"name"}' />
    <input type='hidden' name='contact' value='{"phone": "1233214090","fax":"1098760982"}' />
    <input type="submit" />
</form> 

但现在“action.cfm”页面在 http 请求正文中需要一个 JSON 值。喜欢

{
    "employee": {
        "first_name": "test",
        "last_name": "name"
    },
    "contact": {
        "phone": "1233214090",
        "fax": "1098760982"
    }
}

不确定在这种情况下我们如何在表单 post 中发送 http 请求正文中的 JSON 数据。请建议是否可以这样做,或者是否有任何其他方法可以实现这一点。

【问题讨论】:

  • 我刚刚重新阅读了您的问题...我认为您需要澄清表单的提交方式。您不再使用您显示的表格了吗?
  • 不幸的是,还没有提交 JSON 的官方方法。最好的办法是使用 JavaScript 序列化表单数据并通过 AJAX 发送。
  • 我同意@Alex 所说的。有关类似示例,请参阅此帖子 - stackoverflow.com/a/9142943/1636917
  • /action.cfm 是否被您应用中的其他脚本使用且无法更改? /action.cfm 对收到的 JSON 做了什么?

标签: html forms coldfusion httprequest


【解决方案1】:

在 ColdFusion 中,这是在 post 请求正文中发送 json 的方式:

string function postAsJson(
    required struct data) {

    var responseStr = "";

    try {

        var http = new http(argumentCollection={
            "method": "post",
            "timeout": 50,
            "encodeUrl": false
        });

        http.addParam(type="body", value=serializeJSON(Arguments.data));
        http.addParam(type="header", name="content-type", value="application/json");
        http.setURL("your form handler");

        var httpResult = http.send().getPrefix();

        if (httpResult.status_code == 200) {
            responseStr = httpResult.fileContent;
        }

    } catch (any err) {
        responseStr = "<p>#err.message#</p>";
    }

    return responseStr;
}

myData = {
    "this": "and",
    "that": true
};

result = postAsJson(myData);
writeOutput(result);

在您的请求处理程序中,您会得到如下数据:

requestData = getHttpRequestData();
if (isJSON(requestData.content)) {
    myData = deserializeJSON(requestData.content);
    writeDump(myData);
}
else {
    writeOutput("<p>Invalid request</p>");
}

(我没有在 ACF 中测试过这个,但我知道它在 Lucee - 5.2.x 中确实有效)

【讨论】:

  • 它会重定向到该表单处理程序页面吗?因为用户需要能够浏览该页面。
  • 用户无法导航到请求处理程序并同时将 json 发送到正文。如果您需要在发布请求之后执行某些操作,例如显示某些内容,您可以从表单处理程序中返回并在某处内联显示它。我已经更新了答案以反映这一点。
【解决方案2】:

要将其保存在 ColdFusion 中,您可以在操作页面上获取如下 JSON:

<cfif structKeyExists(form, "employee")><!--- Then form has been submitted --->
    <cfset employeeData = serializeJSON(form)>
</cfif>

【讨论】:

    猜你喜欢
    • 2020-01-24
    • 2013-04-17
    • 2016-10-18
    • 2020-02-28
    • 2018-08-02
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多