i have this code in javascript:
我在javascript中有这个代码:
var oRows= [];
for(var i = 0 ; i < 3 ; i ++) {
var oItem = {name: "example", id: i};
oRows.push(oItem);
}
$.ajax({
url: '/savejson.php',
method: 'post',
data: { 'oRows': oRows }
}).done(function (data) {
console.log(data);
});
and code in the php:
和PHP中的代码:
<?php
$fp = fopen('/data/DecisionTableRows.json', 'w');
fwrite($fp, json_encode($_POST['oRows']));
fclose($fp);
?>
but in the JSON file /data/DecisionTableRows.json
i still get the property Id as string, how i can write it as int?
但是在JSON文件/data/DecisionTableRows.json中,我仍然将属性Id作为字符串,我怎么能把它写成int?
1 个解决方案
#1
2
The problem is that $_POST variables are always strings.
问题是$ _POST变量总是字符串。
To avoid the headache of manually doing an is_numeric
and casting on each one of them in PHP you can do this:
为了避免手动执行is_numeric并在PHP中对每一个进行强制转换,您可以这样做:
var oRows= [];
for(var i = 0 ; i < 3 ; i ++) {
var oItem = {name: "example", id: i};
oRows.push(oItem);
}
$.ajax({
url: '/savejson.php',
method: 'post',
data: { 'oRows': JSON.stringify(oRows) }
}).done(function (data) {
console.log(data);
});
and in PHP
在PHP中
<?php
$fp = fopen('/data/DecisionTableRows.json', 'w');
fwrite($fp, $_POST['oRows']);
fclose($fp);
?>
This way you shift the responsibility of encoding to JSON over to JavaScript which does have the original data to work with.
通过这种方式,您可以将编码的责任转移到JSON,而JavaScript则可以使用原始数据。
#1
2
The problem is that $_POST variables are always strings.
问题是$ _POST变量总是字符串。
To avoid the headache of manually doing an is_numeric
and casting on each one of them in PHP you can do this:
为了避免手动执行is_numeric并在PHP中对每一个进行强制转换,您可以这样做:
var oRows= [];
for(var i = 0 ; i < 3 ; i ++) {
var oItem = {name: "example", id: i};
oRows.push(oItem);
}
$.ajax({
url: '/savejson.php',
method: 'post',
data: { 'oRows': JSON.stringify(oRows) }
}).done(function (data) {
console.log(data);
});
and in PHP
在PHP中
<?php
$fp = fopen('/data/DecisionTableRows.json', 'w');
fwrite($fp, $_POST['oRows']);
fclose($fp);
?>
This way you shift the responsibility of encoding to JSON over to JavaScript which does have the original data to work with.
通过这种方式,您可以将编码的责任转移到JSON,而JavaScript则可以使用原始数据。