【发布时间】:2021-09-11 04:54:14
【问题描述】:
我有 2 个输入的表单,国家名称和国家评级 (0-5) 和提交按钮以添加国家。单击按钮时,它会执行 addCountry 函数。 我总是收到一条错误消息,我不知道为什么 $_POST['country'] 和 $_POST['ratings'] 没有显示。 函数如下所示:
<script>
function addCountry(){
var $country="country";
var $ratings="ratings";
$.ajax({
type:"POST",
url:"../actions/addCountry.php",
data:{ $country: "country", $ratings: "ratings" },
success:function(result){
alert(result);
}
});
}
</script>
php 脚本应该获取国家名称和等级,它看起来像这样:
<?php
if(isset($_POST['country']) &&
isset($_POST['ratings'])){
$country= $_POST['country'];
$ratings = $_POST['ratings'];
echo $country;
echo "is country. You rated it: ";
echo $ratings;
}
else{
echo "Error";
}
?>
HTML 看起来像这样:
<head>
<link rel="stylesheet" href="../styles/styles.css">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript"src= "../actions/mapData.php"></script>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery
3.1.1.min.js"></script>
</head>
<body>
<div id="map" style="width: 90%; height: 20%;"></div>
</body>
<body>
<form autocomplete="off" method="POST">
<div class="autocomplete" style="width:100%;">
<input id="country" type="text" name="country" placeholder="Country">
<label for="ratings"> Rate this country: </label>
<select id="ratings" name="ratings">
<option value="one"> 1 </option>
<option value="two"> 2 </option>
<option value="three"> 3 </option>
<option value="four"> 4 </option>
<option value="five"> 5 </option>
</select>
</div>
<input type="submit" id="add" value="Add Country" onclick="addCountry()"/>
</form>
【问题讨论】:
-
错字。您正在发送名称以美元符号开头的密钥,并在从 _POST 读取时省略它们
-
@Quentin 谢谢。我有另一个问题。如何将值从 传递到 ajax 数据
-
你有向后的键和值:
{ country: $country, ratings: $ratings } -
@Aplexas
$("#country").val() -
也可以使用
$("form").serialize()获取所有表单字段。
标签: javascript php html ajax post