如何将JSON多值写入PHP输入框?多数组代码报错求指导
问题:JSON多值数组写入PHP输入框失败
单值写入功能正常,但处理多值数组时出现错误,相关代码如下:
PHP端请求发送代码
$result[] = array( "No_" => $record['No_'], "Lokasi" => $record['Location'], "MRDate" => $record['MRDate']->format('Y-m-d'), "Description" => $record['Description'], "UOM" => $record['UOM'], "QTY" => $record['QTY'], "Item_No" => $record['Item_No'] ); // Send in JSON encoded form $myJSON = json_encode($result); echo $myJSON; //sqlsrv_free_stmt( $stmt2);
JS端请求接收代码
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); var tempD = myObj[0]; document.getElementById("MRDate").value = tempD; document.getElementById("No_").value = myObj[1]; document.getElementById("lokasi").value = myObj[2]; document.getElementById("Item_No").value = myObj[3]; document.getElementById("Description").value = myObj[4]; document.getElementById("UOM").value = myObj[5]; document.getElementById("QTY").value = myObj[6]; } }; xmlhttp.open("GET", "option_mr.php?List=" + str, true); xmlhttp.send();
错误原因
PHP端生成的JSON是对象数组,结构类似[{"No_":"xxx", "Lokasi":"xxx", "MRDate":"xxxx-xx-xx", ...}],但JS端错误地将其当作普通一维数组,直接用索引myObj[1]等取值——实际上myObj[1]不存在(单条记录场景),就算有多条记录,也应该先取出对象再访问对应属性。
修复方案
场景1:仅处理单条记录
修改JS代码,先取出数组中的对象,再通过键名获取对应值:
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); // 先判断数组非空,避免报错 if (myObj.length === 0) return; // 取出第一条记录的对象 var record = myObj[0]; document.getElementById("MRDate").value = record.MRDate; document.getElementById("No_").value = record.No_; document.getElementById("lokasi").value = record.Lokasi; document.getElementById("Item_No").value = record.Item_No; document.getElementById("Description").value = record.Description; document.getElementById("UOM").value = record.UOM; document.getElementById("QTY").value = record.QTY; } }; xmlhttp.open("GET", "option_mr.php?List=" + str, true); xmlhttp.send();
场景2:处理多条记录(批量填充)
如果PHP返回多条记录,需要循环遍历数组,比如给输入框组添加索引后缀(如MRDate_0、MRDate_1):
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); myObj.forEach(function(record, index) { document.getElementById(`MRDate_${index}`).value = record.MRDate; document.getElementById(`No__${index}`).value = record.No_; document.getElementById(`lokasi_${index}`).value = record.Lokasi; // 其他字段同理 }); } }; xmlhttp.open("GET", "option_mr.php?List=" + str, true); xmlhttp.send();
额外注意事项
- 确保PHP端的键名和JS中调用的键名完全一致(比如PHP用
Lokasi,JS要写record.Lokasi,不要写成小写的lokasi) - 若PHP可能返回空数组,必须先判断
myObj.length > 0再执行取值操作,避免出现Cannot read properties of undefined错误
内容的提问来源于stack exchange,提问作者Phuc Phic
相关产品推荐
相关产品推荐

