我在我的模板中使用JavaScript制作表格。我决定通过JSON交换数据。请求信息和构建表有效,但序列化程序不会验证发送回服务器的JSON数据。
我正在使用Django REST Framework和JQuery。
我的观点
def get_CEMatrix(request, id):
if request.method == 'GET':
Cells = CellCE.objects.filter(project=id).order_by('id')
serializer = CellCESerializer(Cells, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = CellCESerializer(data=data, many = True)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, safe=False)
return JsonResponse(serializer.data, safe=False)
我的JS
alert(JSON.stringify(myRows));
$.ajax({
"type": "POST",
"dataType": "json",
"url": get_CEMatrix,
"data": JSON.stringify(myRows),
"success": function(result) {
alert("success of message to server and result is: " + result);
}
});
串行
class CellCESerializer(serializers.ModelSerializer):
row = serializers.StringRelatedField()
val = serializers.ListField()
class Meta:
model = CellCE
fields = ('row','val')
为模型
class CellCE(models.Model):
project = models.ForeignKey('Project', on_delete=models.CASCADE, default='1')
row = models.ForeignKey('Descriptor', on_delete=models.CASCADE)
val = ArrayField(ArrayField(models.IntegerField(blank=True, default=0)))
我已经实现了一个功能来显示模板中交换的JSON数据。服务器像这样发送JSON:
[
{
"row":"THIS IS AMAZING",
"val":[[139,
144,147],[0,0,0]]
},
{
"row":"HOLY FUCKING MOLY",
"val":[[139,
144,147],[0,0,0]]
},
{
"row":"OMG",
"val":[[139,
144,147],[0,0,0]]
}
]
发送到服务器的JSON看起来像这样。
[
{
},
{
"row":"THIS IS AMAZING",
"val":"139 144 147 "
},
{
"row":"HOLY FUCKING MOLY",
"val":"139 144 147 "
},
{
"row":"OMG",
"val":"139 144 147 "
}
]
序列化程序是否按我认为的方式工作,或者发回的JSON格式不够好。
我愿意接受任何建议。
如果需要,整个JS
// TABLE FUNCION
$(document).ready(function(){
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1);
// TABLE HEADER
for (var i = -1; i < descriptornamelist.length; i++) {
var th = document.createElement("th");
if (i==-1) {
th.innerHTML = "Descriptors";
tr.appendChild(th);
}
else {
th.innerHTML = descriptornamelist[i];
tr.appendChild(th);
}
}
// ADD JSON DATA TO THE TABLE AS ROWS.
//First Load with 1 Complete set of Data
$.getJSON( get_CEMatrix , function(result){
$.each(result, function(index, field){
tr = table.insertRow(-1);
//First COL with Descriptornames
var tabCell = tr.insertCell(0);
tabCell.innerHTML = field["row"];
//Other COLs with Values
for (var i = 0; i < descriptoridlist.length; i++) {
var tabCell = tr.insertCell(-1);
tabCell.contentEditable = true; //change to 1 vor actual values
tabCell.innerHTML = field["val"][0][i]; //change to 1 vor actual values
};
});
});
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("CETable");
divContainer.innerHTML = "";
divContainer.appendChild(table);
});
//BUTTON FOR JSON TO SERVER
$(".table_to_JSON").click(function(){
var myRows = [];
// Loop through grabbing everything
var $rows = $("tbody tr").each(function(index) {
$cells = $(this).find("td");
myRows[index] = {};
$cells.each(function(cellIndex) {
// Set the header text
if( cellIndex == 0) {
myRows[index]["row"] = $(this).text();
}
if( cellIndex > 0) {
if(myRows[index]["val"] === undefined){
myRows[index]["val"] =("");
}
myRows[index]["val"] += $(this).text() + (" ");
}
});
});
alert(JSON.stringify(myRows));
$.ajax({
"type": "POST",
"dataType": "json",
"url": get_CEMatrix,
"data": JSON.stringify(myRows),
"success": function(result) {
alert("success of message to server and result is: " + result);
}
});
});