我有一个JS文件管理我的数据(推送我的JSON对象中的数据等),以及来自CodeIgniter的经典MVC结构文件。CodeIgniter和JSON对象:如何将数据推送到数据库?
我的JS包含我想推入我的数据库的JSON对象。我该怎么办?我怎样才能从我的JS文件到达控制器和模型?我无法弄清楚什么是实现我的目标的正确过程!我发现没有类似于我的问题。
编辑 的推到数据库中的数据是整个JSON object.The数据的一部分来推动,例如:{ "index": 0, "x": 50, "y": 80, "weight": 2, "px": 50, "py": 80, "fixed": 0 }
在我的JS文件,我已经试过这段代码:
$("#hexa-btn").on("click", function() {
$.ajax({
type: "POST",
url: "/prototype/returndata",
data: JSONshapes.shapes[0].nodes[0],
cache: false,
success:
function(data){
console.log(data.index);
console.log(data.x);
console.log(data.y);
}
});
});
我的控制器具有这样的功能:
function returndata(){
$index = $this->input->post('index');
$x = $this->input->post('x');
$y = $this->input->post('y');
$weight = $this->input->post('weight');
$px = $this->input->post('px');
$py = $this->input->post('py');
$fixed = $this->input->post('fixed'); ;
echo json_encode(array('node'=>$node));
}
我不知道在所有关于这个功能。看起来这是模型的角色来完成这项工作,不是吗?
第二编辑所以,我尝试了@Harish Lalwani的解决方案,但这次与我的节点阵列(不只一个)。我有JavaScript文件中有以下功能:
function sendNode(){
var node_url = "/prototype/insert_node";
var data_node = JSON.stringify(JSONshapes.shapes[0].nodes);
$.post(node_url, {'node_data': data_node}, function(data){
console.log(data.index);
});
}
,并在控制器下面的一个(感谢到this post):
function insert_node(){
$node_data = $this->input->post('node_data');
$node_data = json_decode($node_data,true);
echo 'Your Data: ' . $node_data[0]['index'];
},
但是,打印数据的时候,我得到undefined
。变量data_node
是下面的(所以,是一个数组):
[{"index":0,"x":50,"y":80,"weight":2,"px":50,"py":80,"fixed":0},{"index":1,"x":189,"y":107,"weight":2,"px":189,"py":107},{"index":2,"x":95,"y":145,"weight":2,"px":95,"py":145}]
现在,我不知道了该怎么办!我发现真的太少例子。任何人都可以让我摆脱苦难吗?非常感谢您提前!
使用$ .ajax.post –
显示你的代码,你尝试过什么? – CodeGodie