如何将Excel转JSON并发送至CFC入库?遇400错误求排查
解决Excel转JSON后通过Ajax发送到ColdFusion CFC时的400错误问题
我帮你排查下代码里的问题,400 Bad Request通常和请求格式、参数传递方式有关,咱们一步步来解决:
前端代码的问题及修复
1. 默认GET请求触发长度限制
jQuery的$.ajax默认使用GET请求,而你把整个Excel转成JSON字符串后,数据量可能很大,GET请求的URL长度有浏览器/服务器限制,这直接导致了400错误,必须改成POST请求。
2. 未设置正确的Content-Type
发送JSON数据时,需要明确告诉服务器请求体的格式,同时调整数据传递方式——直接把JSON字符串放在请求体中,而不是塞进键值对参数里。
修复后的前端代码
var selectedFile = evt.target.files[0]; var reader = new FileReader(); reader.onload = function(event) { var data = event.target.result; var workbook = XLSX.read(data, { type: 'binary' }); workbook.SheetNames.forEach(function(sheetName) { var excel_json = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]); var json_object = JSON.stringify(excel_json); $.ajax({ url:"maps.cfc?method=updateFuelPrices", // 将method参数放在URL中 type: "POST", // 切换为POST请求 dataType: "json", contentType: "application/json", // 指定请求体格式为JSON data: json_object, // 直接发送JSON字符串 success: function(data) { console.log(data); console.log("update successful"); }, error: function(xhr, textStatus, errorThrown) { console.log(textStatus); console.log(errorThrown); console.log("Something went wrong! Please refresh the page and try again."); } }) }) }; reader.onerror = function(event) { console.error("File could not be read! Code " + event.target.error.code); }; reader.readAsBinaryString(selectedFile);
ColdFusion CFC的调整
现在前端直接发送JSON请求体,CFC需要读取请求体内容,而不是通过URL参数接收。你原来的参数传递方式已经不适用,需要修改为读取请求体并反序列化为结构:
修复后的CFC函数代码
<cffunction name="updateFuelPrices" output="false" access="remote" returnformat="json" returntype="string"> <!--- 读取POST请求体中的JSON内容 ---> <cfset requestBody = toString(getHttpRequestData().content)> <cfset jsstruct = deserializeJSON(requestBody)> <cfset returntext = 'json sent successfully...'> <cfdump var="#jsstruct#" output="console"> <!--- 输出到CF日志,避免干扰返回的JSON格式 ---> <!--- DB insert query to go here ---> <cfreturn returntext> </cffunction>
额外提示
- 如果Excel有多个sheet,当前代码会为每个sheet单独发一次请求,数据量大时可以考虑合并成一个请求发送,减少服务器压力。
- 测试时可以先在前端用
console.log(json_object)检查JSON格式是否正确,避免语法错误。 - CFC里的
<cfdump>一定要加output="console",否则dump的内容会混入返回的JSON中,导致前端解析失败。
内容的提问来源于stack exchange,提问作者Amruta
相关产品推荐
相关产品推荐

