[英]Json stringify in JS and decoding in php
js JS
var sim_list=[];
var simvalue = $('input[name="simnamecbx"]:checked').each(function(){
var sim_name=this.value.split(" ")[0];
console.log("simname:",sim_name);
sim_list.push({
sim_name
});
);
console.log(sim_list);
var simulation_list = JSON.stringify(sim_list);
$.ajax({ url: 'addprogram.php',
data: {addpgmname:addprogname, addpgmcomp:addprogcomp, addpgmdate:addprogdate, simselvalue:simulation_list},
type: 'post',
dataType: 'json',
success: function(output){
var a = output;
console.log(a);
}
});
php PHP
$simvalue = json_decode($_POST["simselvalue"],true);
foreach($simvalue as $key => $value) {
print_r($value);
}
Question 题
When I execute the above php I get the values as 当我执行上述php时,我得到的值为
Array
(
[0] => Array
(
[sim_name] => 12
)
[1] => Array
(
[sim_name] => 13
)
[2] => Array
(
[sim_name] => 14
)
)
But I want the result to be like 12, 13, 14 which can be inserted into mysql table. 但是我希望结果像12、13、14一样可以插入到mysql表中。 Please explain how to parse this array that I get from javascript. 请解释如何解析我从javascript获得的数组。
I think that the problem is that you are pushing an object with sim_name
on to your array instead of the actual value. 我认为问题在于您正在将具有sim_name
的对象推送到数组而不是实际值。 This actually only works in ES6 compatible browsers which makes your error invisible. 这实际上仅在与ES6兼容的浏览器中有效,这使您的错误不可见。
The problem is this part in your javascript code: 问题是您的JavaScript代码中的这一部分:
sim_list.push({
sim_name
});
In ECMAScript 6 this is the equivalent of the following: 在ECMAScript 6中,这等效于以下内容:
sim_list.push({
sim_name: sim_name
});
Thus you are pushing an object with the sim_name
property set to the number (eg 12, 13, 14). 因此,您正在推送sim_name
属性设置为数字的对象(例如12、13、14)。
What I think that you want to do is the following: 我认为您要执行以下操作:
sim_list.push(sim_name)
This will push only the number onto the array. 这只会将数字压入阵列。
All together now: 现在都在一起了:
JS JS
var sim_list = []
$('input[name="simnamecbx"]:checked').each(function () {
var sim_name = this.value.split(' ')[0]
sim_list.push(sim_name)
})
var data = {
addpgmname: addprogname,
addpgmcomp: addprogcomp,
addpgmdate: addprogdate,
simselvalue: JSON.stringify(sim_list)
}
$.ajax({
url: 'addprogram.php',
data: data,
type: 'post',
dataType: 'json',
success: function (output) {
console.log(output)
}
})
PHP PHP
$simvalue = json_decode($_POST["simselvalue"]);
print("The selected values was: " . implode($simvalue, ", "));
Easiest way: 最简单的方法:
$data = json_decode($_POST["simselvalue"], true) // true = associative array
foreach($data as $key => $value) {
// database query
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.