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