有人可以帮助我吗? 我收到此错误:
"Notice: Undefined index: name in C:\xampp\htdocs\test.php on line 2
我想知道如何在ajax语句中传递多个值,例如:
data: {name: "john", country: "UK"}
在服务器端检索它,最后将其发布回初始页面。
客户端:
<script>
$(document).ready(function(){
$("#btn").click(function(){
$.ajax({
type: "POST",
url: "test.php",
data: {name: "John"}
})
.done(function() {
$("#output").load("test.php");
});
});
});
</script>
<form>
<input type="button" value="Test" id="btn" />
</form>
<div id="output"> </div>
服务器端:
<?php
$student =(string) $_POST['name'];
//$student = isset($_POST['name'])?$_POST['name']:'err';
$message = "Name: ".$student;
echo ($message);
?>
You are loading the test.php
file twice: Once with your POST request, which returns the correct data... but then you are ignoring that data and requesting it again with a GET request, which of course has no POSTdata attached.
Try:
.done(function(data) {
$("#output").html(data);
});
Try something like this:
$("#btn").click(function(){
$.ajax({
type: "POST",
url: "test.php",
data: {name: "John"},
success: function(data) {
$("#output").html(data);
}
})
You can also add more data just as you said:
data: {name: "John", country:"UK"}
And in PHP, you'll get them as $_POST['country']
.
To pass multiple data items over Ajax from a form you can do this for example which takes the values from the input fields and passes them through:
data:
'forename=' + $('#forename').val() +
'&surname=' + $('#surname').val() +
'&addressLine1=' + $('#addressLine1').val(),