如何将JSON对象传递给PHP [英] How to pass JSON object to PHP
问题描述
我在下面有以下代码段.单击创建订单"按钮时,用户输入的数据(代码中未显示)将通过功能"convertToJson"转换为JSON.我能够将数据转换为JSON.我的问题是将JSON对象传递给PHP,以便可以将对象插入数据库.当我运行$ var_dump时,PHP返回"Null"值.
I have the following code snippet below. When the "Create Order" button is clicked, the user inputted data (not shown in the code) is converted to JSON, via the function "convertToJson". I am able to convert the data to JSON. My problem is passing the JSON object to PHP so that I can insert the object to the database. PHP is returning a "Null" value when I run $var_dump.
请注意,我正在尝试发布到同一页面,即"orders.php"
Note that I am trying to POST to the same page, which is "orders.php"
<head>
<script type="text/javascript">
function convertToJson()
{
var tableData = $('#productOrder').tableToJSON({
ignoreColumns: [0]
});
var xhr = new XMLHttpRequest();
xhr.open("GET","orders.php",true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(tableData));
}
</script>
</head>
...more code...
<button type="button" class="btn btn-success btn-md" style="float: right;" onclick="convertToJson();">Create Order</button>
<div>
<?php
$data = json_decode(file_get_contents('php://input'));
var_dump($data);
?>
</div>
推荐答案
您应该使用实际的ajax请求来发布数据
you should use an actual ajax request to do post your data
$.ajax({
url: 'yourscript',
type: 'POST',
data: { data: tableData }
dataType: "json",
beforeSend: function() {
//do something
}
}).done(function(msg){
//do something when done
}).fail(function(msg){
//error handling
}).complete(function(msg){
//do something when completed
});
}
并使用$ _POST ["data"]
and get the data with $_POST["data"]
还请注意,如前所述,您现在需要处理脚本生命周期,因为现在您正在处理异步请求
also note that as stated before you need to take care of your script lifecycle as you are now working with async requests
这篇关于如何将JSON对象传递给PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!