我有这样的 HTML 文件:
<script>
$(document).ready(function () {
$("#btn").click( function() {
var id = $('#id').val();
var name = $('#name').val();
var Address = $('#Address').val();
$.ajax({
url: "http://localhost/connection.php",
type: "POST",
data : { topost: JSON.stringify({id: id, name: name, Address: Address}) },
//I ASSUME HERE IM PASSING MY THREE FIELDS id, name and Address
//IN A STRING CALLED 'TOPOST' TO MY FILE CONNECTION.PHP
//WHICH IS HOSTED ON MY LOCALHOST, IM USING XAMPP.
datatype: "jsonp",
success: function (status) {
if (status.success == false) {
alert("Failure!");
}
else {
alert("Success!");
}
}
});
return false;
});
});
</script>
现在,在connection.php
我的本地主机上托管的文件中,我正在尝试读取这三个字段,以便我可以将所有三个字段放入数据库(MySQL)中。
但是,我得到的错误是:
Connected to database!<br />
<b>Notice</b>: Undefined index: topost in <b>C:\xampp\htdocs\connection.php</b> on line <b>27</b><br />
<br />
<b>Notice</b>: Undefined index: topost in <b>C:\xampp\htdocs\connection.php</b> on line <b>29</b><br />
我的问题是:
为什么'topost'未定义?我如何connection.php
理解我正在从名为“topost”的变量中的 HTML 文件中发送 JSON 数据?
因此,请仔细阅读以下 PHP 文件并提出错误建议。
服务器端 PHP 文件:
<?php
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
$server = "localhost";
$username = "root";
$password = "";
$database = "jqueryex";
$con = mysql_connect($server, $username, $password);
if($con) { echo "Connected to database!"; }
else { echo "Could not connect!"; }
//or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$posteddata = $_POST['topost'];
$thedata= json_decode($_POST['topost']);
echo ($thedata);
mysql_close();
?>