javascript jquery将mysql中的json对象保存为字符串

时间:2016-11-03 09:31:13

标签: jquery mysql json object

我想在桌子上保存一个对象。

我的代码:

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
var ArticleNo = 373737373737;
var objectArticleNo = {};
objectArticleNo['person'] = person;
objectArticleNo['articleNo'] = ArticleNo;

var addArticleNoToDB = function(objectArticleNo) {

$.ajax({
  type: "POST",
  url: "php/__addArticleNo.php",
  data: {my_json_data: JSON.stringify(objectArticleNo)},
  dataType: "text",
  success: function (msg, string, jpXHR) {
    console.log(msg);
  },
  error: function(xhr, desc, err) {
    console.log(xhr);
    console.log("Details: " + desc + "\nError:" + err);
  }
});
}

PHP:

<?php
$item = $_POST['my_json_data'];
$obj = json_decode($item, true);

$person = $obj['person'];
$articleNom = $obj['articleNo'];

$queryArticle = "INSERT INTO articleNo (articleNom, personAsJsonString) VALUES ($articleNom, $person)";

if(mysqli_query($connection, $queryArticle)) {
   echo "yes";
} else {
    echo "nope";
}

该对象将保存为“数组”。但我打算将'person'对象保存为像

这样的字符串
'{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}'

我是否必须再次解析它或者问题是什么?

2 个答案:

答案 0 :(得分:0)

这是因为你首先使用json_decode解码json字符串。它是PHP中的数组。在将数组插入表中之前,您可以尝试将数组再次编码为json。

$person_json = json_encode($obj['person']);
$queryArticle = "INSERT INTO articleNo (articleNom, personAsJsonString) VALUES ({$articleNom}, '{$person_json}')";

答案 1 :(得分:0)

为什么不将person对象作为字符串本身发送 -

var person = JSON.stringify({firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"});
var ArticleNo = 373737373737;
var objectArticleNo = {};
objectArticleNo['person'] = person;
objectArticleNo['articleNo'] = ArticleNo;

var addArticleNoToDB = function(objectArticleNo) {

$.ajax({
  type: "POST",
  url: "php/__addArticleNo.php",
  data: {my_json_data: JSON.stringify(objectArticleNo)},
  dataType: "text",
  success: function (msg, string, jpXHR) {
    console.log(msg);
  },
  error: function(xhr, desc, err) {
    console.log(xhr);
    console.log("Details: " + desc + "\nError:" + err);
  }
});
}