【发布时间】:2018-10-17 15:00:27
【问题描述】:
我需要将数组发送到我的 mysql 数据库。
我创建了一个 JSON 数组,但不知道如何将其发布到 php 以传输到 db。
$( function () {
$( '#orderForm' ).on( 'submit', function ( event ) {
event.preventDefault();
var myData = [],
keys = ['item', 'qty', 'price'],
url = this.action;
$( '#orderTable' ).find( 'tr:gt(0)' ).each( function ( i, row ){
var oRow = {};
$( row ).find( 'td' ).each( function ( j, cell ) {
oRow[keys[j]] = $( cell ).text();
} );
myData.push( oRow );
} );
console.log( myData );
console.log( JSON.stringify( myData ) );
} );
} );
我需要将其发布到数据库item->item、qty->qty、price->price。
我试过了:
$.ajax( {
url: 'tc_menu',
type: 'POST',
data: JSON.stringify( myData ),
success: function ( data ) {
console.log( "success:", data );
},
failure: function ( errMsg ) {
console.error( "error:", errMsg );
}
} );
数据存储整个页面,但不存储(stringified myData)。而且我仍然无法在 $_POST 和 json_decode 的 php 代码中得到它
数据存储整个页面,但不是stringified myData,我无法通过$_POST 和json_decode 在php 代码中获取它
php代码
`if(isset($_POST['submitted_m'])){
$myData = serialize($_POST['data']);
$sqli = "INSERT INTO tc_cafe_orders SET item='".$myData."' ";
if (mysqli_query($db, $sqli)) {
$msg = "New Order added!";
echo "<script>
alert(\"$msg\");
window.location.replace('tc_menu.php');
</script>";}
else {echo "Error:".$sql."<br>".mysqli_error($db);}}`
【问题讨论】:
-
问题小解释!!!需要更多。
-
你有很多双倍的代码行。请改正。并添加有关
console.log( JSON.stringify( myData ) );和json_decode($_POST['data'])的详细信息 -
@Anton 已更正,谢谢!
console.log(JSON.stringify( myData ) );输出以控制台将数据从表传输到 JSON 的结果。json_decode($_POST['data'])将数据解码为字符串,以便发布到 mysql 表中。
标签: javascript mysql arrays json post