如何发布此数组并在 php 中打印

How to post this array and print in php?

本文关键字:php 打印 何发布 数组      更新时间:2023-09-26

如何将这个数组发送回服务器,以便我可以在PHP中处理它?

<script>
var myJSONObject = {
        "onw": [ 
            {"name": "nilesh", "age": "31", "sal": "4000"},
            {"name1": "nitin", "age": "11", "sal": "14000"}]
};
document.write(myJSONObject.join());
</script>

您可以使用序列化方法。 即序列化JavaScript变量并将其传递给PHP,在PHP文件中您可以反序列化相同的变量。

序列化:在jQuery中序列化为JSON

参考: http://api.jquery.com/serializeArray/

永远不要使用 document.write 因为它已经过时了,将元素添加到 DOM 的首选方法是使用 appendChild

用于追加的示例代码:

var textNode = document.createTextNode("some text"); // creates new text node
    textNode.appendChild(document.body); // adds to the end of the body

对于使用 jquery 将数据发布到 php:

在将其发送到服务器之前,您需要使用 JSON.stringify 将其格式化为字符串

var formattedData = JSON.stringify(myJSONObject )

$.ajax({
  type: "POST",
  url: "server.php",
  data: formattedData ,
  dataType: 'json',
  success: function () {
     alert("Data posted to php and processed succesfully"); 
  }
});

var json_text = JSON.stringify(myJSONObject, null, 2);

警报(json_text);