目前,我认为有一个可编辑的表,该表是从带有javscript函数的启动json创建的。在这个表中,可以更改json的每个字段。我目前正在寻找一种方法来传递这个用户编辑的json一旦一个按钮被点击。问题是我从来没打过Ajax电话..。
首先,我认为:
{% extends 'default/index.html.twig' %}
{% block content %}
<div class="json-view"> <!-- here is where I print my table -->
</div>
{% endblock %}
{% block javascripts %}
// Here is where I execute all the function below
{% endblock %}这是我的开场白:
[{"a" : 0, "b" : 7, "c": "/", "d" : 5, "e" : "/", "f" : 5, "g" : "/"},
{"a" : 0.1, "b" : 15, "c": 30, "d" : 10, "e" : 30, "f" : 10, "g" : 30},
{"a" : 0.2, "b" : 15, "c": 30, "d" : 10, "e" : 30, "f" : 10, "g" : 30},
{"a" : 0.3, "b" : 15, "c": 30, "d" : 10, "e" : 30, "f" : 10, "g" : 30},
{"a" : 0.4, "b" : 15, "c": 30, "d" : 10, "e" : 30, "f" : 10, "g" : 30},
{"a" : 0.5, "b" : 15, "c": 30, "d" : 10, "e" : 30, "f" : 10, "g" : 30},
{"a" : 0.6, "b" : 20, "c": 30, "d" : 20, "e" : 30, "f" : 15, "g" : 30},
{"a" : 0.7, "b" : 20, "c": 30, "d" : 20, "e" : 30, "f" : 15, "g" : 30}]这是我用来创建可编辑表的javascript函数:
function jsonToTable(json, opts={}) {
let headers = Object.keys(json[0]);
let table = document.createElement('table');
let thead = document.createElement('thead');
let tbody = document.createElement('tbody');
let thead_tr = document.createElement('tr');
if (opts.class) table.classList.add(opts.class);
headers.forEach(header => {
let th = document.createElement('th');
th.textContent = header;
thead_tr.appendChild(th);
});
json.forEach(record => {
let tr = document.createElement('tr');
headers.forEach(field => {
let td = document.createElement('td');
td.textContent = record[field];
td.setAttribute('contenteditable', true);
tr.appendChild(td);
});
tbody.append(tr);
});
thead.appendChild(thead_tr);
table.appendChild(thead);
table.appendChild(tbody);
return table;
}这是我用来从表中取回编辑后的值的函数:
function tableToJson(table, options={}) {
let fields = Array.from(table.querySelectorAll('thead tr th')).map(th => th.textContent);
return Array.from(table.querySelectorAll('tbody tr')).map(tr => {
return Array.from(tr.querySelectorAll('td')).reduce((record, td, index) => {
return Object.assign(record, { [fields[index]] : formatValue(td.textContent) });
}, {});
});
}我必须将表返回给控制器,因为我必须在控制器中修改它,并将其保存在数据库中。
有什么办法吗?
发布于 2020-03-23 10:17:36
你当然可以!这是ajax调用:
$.ajax({
url : "path('ajax_call_for_table')",
type: "POST",
data : table_data,
success: function() { // some code on success }
});其中table_data是要修改的数据。
然后,您必须在控制器中创建一个方法来处理这个ajax调用:
/**
* @Route("/ajax/table-data", name="ajax_call_for_table")
* @Method("POST")
*/
public function setTableData(Request $request)
{
if ($request->isXmlHttpRequest()) { // <- Check that is an ajax call
$em = $this->getDoctrine()->getManager();
$table_data = $request->request->get('table_data'); // <- Get the *data* of ajax
/** Do something with this data */
return new Response();
}
}请注意,此方法的名称必须与ajax调用的url中使用的名称相同。
对不起,我的英吉利斯。
https://stackoverflow.com/questions/60757794
复制相似问题