我们有一个表单,正在将数据提交到新标签页中。喜欢,
<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"
}
}
在这种情况下,不确定如何在表单请求中的http请求正文中发送JSON数据。请建议是否可以这样做,或者是否有其他方法可以实现此目的。
答案 0 :(得分:2)
在ColdFusion中,这是在发布请求的正文中发送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中确实有效)
答案 1 :(得分:0)
要将其保留在ColdFusion中,可以在操作页面上获取如下的JSON:
<cfif structKeyExists(form, "employee")><!--- Then form has been submitted --->
<cfset employeeData = serializeJSON(form)>
</cfif>