我花了几个小时一步一步地测试我的所有代码,但仍然无法使其工作。我最终得到了php文件来将测试对象发送到mysql数据库,但我仍然无法让jQuery ajax帖子连接到php。任何人都可以发现问题吗?运行代码时收到"500 内部服务器错误"消息。
Javascript:
var jsonEntry = {"timestamp":"2015/01/21 22:18:00","note":"hi there","tags":["one", "two"]};
// send json converted object to php file via ajax
$("#sendButton").click(function () {
$.ajax({
url: 'php/ajax.php',
type: 'POST',
dataType: 'JSON',
data: jsonEntry,
error :
function(xhr, status, error) {
alert(xhr.status);
alert(error);
},
success :
function(data) {
console.log('send success');
}
});
});
来自"ajax.php:"的PHP代码
<?php
if(isset($_POST["data"])) {
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$timeStamp = $obj[timestamp]; //added semicolon here
$note = $obj[note];
$tags = $obj[tags];
//Connecting to a database
//Connection info
$hostname = "localhost";
$username = "root";
$password = "root";
//Code to connect
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Select database to work with
$selected = mysql_select_db("notes", $dbhandle)
or die("Could not select examples");
//Execute SQL query and return records
mysql_query("INSERT INTO notes (dateAndTime, noteBody, noteTags) VALUES ('$timestamp', '$note', '$tags')");
// Close the connection
mysql_close($dbhandle);
}
?>
更新:我已经在 php 文件中需要的地方添加了分号,但现在收到错误 200,"语法错误:JSON 解析错误:意外的 EOF"。
我认为问题是这里缺少分号:
$timeStamp = $obj[timestamp]
修复此错误后,切换此行:
$json = file_get_contents('php://input');
自:
$json = $_POST['data'];