我有一个HTML文件,其中包含如下各种字段(我将只展示一个示例,因为其余的都是相同的):
<map name="parcerlas">
<area shape="poly" coords="618,4,618,74,681,76,683,56,684,39,684,27,683,14,682,4" href="#" alt="Parcela 9" title="Parcela 9" onclick="getdata('9');">
</map>
使用函数getdata()
,我检索ID
里面,我需要通过这个ID
使用AJAX到另一个PHP文件,并在新文件中使用它。我怎样才能做到这一点呢?
下面是我的getdata()
函数:
<script type="text/javascript">
function getdata(id){
alert(id);
$.ajax({
type: "POST",
url: "activations.php",
data:
{
id;
}
}
</script>
您需要指定数据的键:
data: { 'id': id }
也有语法错误在你的代码片段:
function getdata(id){
alert(id);
$.ajax({
type: "POST",
url: "activations.php",
data: {
'id': id // < no need for semi-colon, properties are key->value based, 'key': value
}
}); // << no closing bracket and semi-colon
} // << close your function
可以在activation。php:
中访问$_POST["id"]
总是检查是否为isset:
if (isset($_POST["id"])) $id = $_POST["id"]; else exit;
回答OP的特殊问题:
你需要打开一个PDO连接到你的SQL服务器(例如MySQL)
if (isset($_POST["id"])) $id = $_POST["id"]; else exit;
$db = new PDO('mysql:host=localhost;dbname=yourdb;charset=utf8',
'username',
'password'); // Open a connection to your database
$q = $db->prepare("SELECT * FROM achievements WHERE id=?"); // Get all achievements where id=$id
$q->execute(array($id)); // Run the query
$rows = $q->fetchAll(); // Fetch the query, associated array
echo json_encode($rows); // Convert the $rows to json, so javascript can read it
您必须将ajax请求的数据类型设置为JSON或使用$.parseJSON(data);
自行解析数据
您可以通过在ajax中添加成功函数来使用返回的数据:
function getdata(id){
alert(id);
$.ajax({
type: "POST",
url: "activations.php",
data: {
'id': id // < no need for semi-colon, properties are key->value based, 'key': value
},
success: function(data) {
var achievements = $.parseJSON(data);
// use achievements variable
}
}); // << no closing bracket and semi-colon
} // << close your function
您有一些拼写错误(Ajax调用中没有右括号,不需要的分号等),但主要需要将数据作为键值对提供。注意:只有当键名不是单个单词(没有空格或连字符/-等)时才需要引号:
<script type="text/javascript">
function getdata(id){
alert(id);
$.ajax({
type: "POST",
url: "activations.php",
data:
{
id: id
}
});
}
</script>
将id;
更改为'id':id
并且不使用分号(;
)