How can we pass the JSON data in http request body in form post

独自空忆成欢 提交于 2020-01-06 05:50:45

问题


We had a form which was submitting the data to a page in a new tab. Like,

<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> 

But now "action.cfm" page is expecting a JSON value in http request body. Like

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

Not sure how could we send the JSON data in http request body in form post in this case. Please suggest if it is possible to do so or if there is any other approach to achieve this.


回答1:


In ColdFusion, this is how you send json in the body of a post request:

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);

And in your request handler, you get the data like this:

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

(I have not tested this in ACF, but I know that it does work in Lucee - 5.2.x)




回答2:


To keep it within ColdFusion, you could obtain a JSON as follows, on the action page:

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


来源:https://stackoverflow.com/questions/52820121/how-can-we-pass-the-json-data-in-http-request-body-in-form-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!