我花了几个小时一步一步地测试我的所有代码,但仍然无法使其正常工作。我最终得到了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,&#34;语法错误:JSON解析错误:意外的EOF。&#34;
答案 0 :(得分:1)
我认为这个问题是缺少分号:
$timeStamp = $obj[timestamp]
修复此错误后,您可以切换此行:
$json = file_get_contents('php://input');
为:
$json = $_POST['data'];