我想發送表單數據和js數組到mysql數據庫。我有接收js數組到我的PHP的問題。我從窗體接收數據,但不是數組。我找不到問題。無法接收js數組發佈與ajax
的index.php
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><!--bootstrap-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script><!--jquery-->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script><!--angular js-->
<script type="text/javascript" src="assets/js/main.js"></script>
</head>
<body>
<form method="post" action="upload.php">
<!--dynamic form created from javascript-->
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>
</body>
</html>
的JavaScript - main.js
var objArray = []; //Array of questions
function upload(){
var jsonArray = JSON.stringify(objArray);
$.ajax({
type:'post',
url: 'upload.php',
data: { jsonData : jsonArray},
success: function(data){
console.log("success!");
}
});
} else {
console.log("no data javascript!");
}
}
upload.php的
<?php
if(($_SERVER['REQUEST_METHOD'] == "POST") && (isset($_POST['submit']))){
$servername = "......";
$username = "......";
$password = "......";
$dbname = ".....";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(!empty($_POST['jsonData'])){
$json = $_POST['jsonData'];
var_dump(json_decode($json, true));
echo "<script type=\"text/javascript\">
console.log('received data');
</script>";
} else {
echo "data not received";
}
$conn->close();
}else {echo "unsecure connection";}
?>
objArray看起來是這樣的:
[{"questionId":1,"questionTypeObj":"single","options":3},{"questionId":2,"questionTypeObj":"single","options":3}]
所
upload.php的輸出的「數據沒有收到」
當你點擊按鈕的代碼
請忽略main.js中的「else」語句。 – Bhups
您是否嘗試過'print_r($ _ POST)'?而且你不應該提交你的表單!您應該決定是否使用ajax,或者將其作爲通常的郵寄表單提交。既然你使用了ajax(whats實際用於防止重新編碼頁面),你應該從你的update.php中獲得一個回調函數的結果數據。類似'$ .ajax(...)。complete(function(response){...})'但要小心,您可能需要異步調用您的ajax函數。取決於你在做什麼。 – Dwza