[英]PHP Undefined index data when I try to POST from Ajax
我正在嘗試使用對PHP文件的Ajax POST請求更新mysql數據庫,但收到以下錯誤:
Notice: Undefined index: data in C:\xampp\htdocs\php\php\post.php on line 2
Notice: Undefined index: data in C:\xampp\htdocs\php\php\post.php on line 2
{"d":true}{"d":true}
這是我的Ajax代碼:
$('#addbut').click(function()
{
console.log($("#firstteam").val());
console.log($("#score1").val());
console.log($("#score2").val());
console.log($("#secondteam").val());
var data = {
firstteam:$("#firstteam").val(),
secondteam:$("#secondteam").val(),
score1:$("#score1").val(),
score2:$("#score2").val()}
$("#firstteam").val('');
$("#secondteam").val('');
$("#score1").val('');
$("#score2").val('');
$.ajax({
type: "POST",
url: "php/post.php",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType:'json',
//if received a response from the server
success: function(response)
{
var res = response.d;
if (res == true)
{
$("#error").html("<div><b>Success!</b></div>"+response);
updateTable();
}
//display error message
else {
$("#error").html("<div><b>Information is Invalid!</b></div>"+response);
}
},
//If there was no resonse from the server
error: function(jqXHR, textStatus, errorThrown)
{
console.log("Something really bad happened " + textStatus);
$("#error").html(jqXHR.responseText);
}
});
});
這是我的PHP代碼:
<?php
$data = $_POST['data'] or $_REQUEST['data'];
$js = json_decode($data,true);
$t1 = $js['firstteam'];
$t2 = $js['secondteam'];
$s1 = $js['score1'];
$s2 = $js['score2'];
updateFunction($t1,$s1,$s2);
updateFunction($t2,$s2,$s1);
function updateFunction($name, $s1, $s2)
{
$conn = new mysqli("localhost:3306","root","","leagues");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($s1 > $s2)
$sql = "UPDATE league SET playedgames=playedgames + 1,wongames = wongames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."', points = points + 3 WHERE teams='".$name."'";
else
if ($s1 == $s2)
$sql = "UPDATE league SET playedgames=playedgames + 1,tiegames = tiegames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."', points = points + 1 WHERE teams='".$name."'";
else
if ($s1 < $s2)
$sql = "UPDATE league SET playedgames=playedgames + 1,lostgames = lostgames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."' WHERE teams='".$name."'";
if ($conn->query($sql) === TRUE)
{
$response = json_encode(array('d' => true));
echo $response;
}
$conn->close();
}
?>
我嘗試了一些建議,但是我不知道為什么我的PHP代碼無法正確解析數據。 我的Ajax函數中的Console.log完全打印出我想要的內容。
它不起作用,因為
$.ajax({
...
data: '{"key":"value"}',
...});
您只需將原始格式的字符串( {"key":"value"}
)放入請求正文中。 因此,沒有名為data
表單參數。
要從正文中檢索原始數據,請使用:
$data = file_get_contents('php://input');
OR
$data = stream_get_contents(STDIN);
代替
$data = $_POST['data'] or $_REQUEST['data'];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.