尝试使用ajax将变量发送到php。
js:
var test1 = "test"
$.ajax({
type : "POST",
url : "getid.php",
data: {test1 : test1},
success: function() {
console.log("message sent!");
}
});
控制台中出现"消息已发送!"
php:
<?php
$test1 = $_POST['test1'];
echo $test1;
?>
错误消息:
Notice: Undefined index: test1...
我真的不明白我在这里做错了什么。。。有什么想法吗?
执行`时更新*
$.ajax({
type : "POST",
url : "getid.php",
data: {"test1" : test1},
success: function(msg) {
console.log("message sent!");
console.log(msg);
}
});
此日志记录"测试"
尽管如此,php中仍然会出现相同的错误。。
更改jQuery代码:
var test1 = "test"
$.ajax({
type : "post",
url : "getid.php",
data: {"test1" : test1}, // this is the row that was causing the problem
success: function(msg) {
console.log(msg);
}
});
您必须将test1
放在引号中,因为它是一个包含"测试"的定义变量,导致数据为{"test":"test"}
因为响应是作为参数提供给回调函数的。试试这个
var test1 = "test"
$.ajax({
type : "POST",
url : "getid.php",
data: {"test1" : test1},
success: function(data) { // data argument here
console.log("message sent!");
console.log("data:",data); // log it out here
}
});