【发布时间】:2015-01-22 07:32:15
【问题描述】:
我花了几个小时逐步测试我的所有代码,但仍然无法使其正常工作。我最终得到了 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,“SyntaxError: JSON Parse error: Unexpected EOF。”
【问题讨论】:
-
请在此处添加您的 ajax.php 代码。
-
如果你得到错误 500 总是因为 PHP 端有问题,在这种情况下是 Rob M 所说的分号。
标签: javascript php jquery mysql ajax