我在将变量传递给php页面时遇到问题。
以下是代码:
var varFirst = 'something'; //string
var varSecond = 'somethingelse'; //string
$.ajax({
type: "POST",
url: "test.php",
data: "first="+ varFirst +"&second="+ varSecond,
success: function(){
alert('seccesss');
}
});
PHP:
$first = $_GET['first']; //This is not being passed here
$second = $_GET['second']; //This is not being passed here
$con=mysqli_connect("localhost","root","pass","mydb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO mytable (id, first, second) VALUES ('', $first, $second)");
mysqli_close($con);
}
我错过了什么?实际数据保存到数据库BUT $ first,$ second值没有传递给php文件。
答案 0 :(得分:2)
您正在使用POST类型,在POST中检索它:
$first = $_POST['first'];
$second = $_POST['second'];
或者更改你的JQuery调用:
$.ajax({
type: "GET",
url: "test.php",
data: "first="+ varFirst +"&second="+ varSecond,
success: function(){
alert('seccesss');
}
});
答案 1 :(得分:2)
这是因为你正在传递数据抛出POST
方法,并尝试使用GET
来改变这两行
$first = $_POST['first']; //This is not being passed here
$second = $_POST['second']; //This is not being passed here
或者只是将您的方法更改为jquery中的GET
type: "GET"
答案 2 :(得分:1)
您在ajax中使用类型:“POST”并尝试使用$ _GET获取,请尝试
$first = $_REQUEST['first']; //This is not being passed here
$second = $_REQUEST['second'];
答案 3 :(得分:1)
还有一种传递数据的方法
$.ajax({
type: "POST",
url: "test.php",
data: {first: varFirst,second: varSecond},
success: function(){
alert('seccesss');
}
});
你可以使用
$_POST['first'];
$_POST['second'];
希望它有所帮助。