[英]Trying to pass variable from JavaScript to PHP using Ajax but got error " Undefined array key"
[英]Trying to Pass JavaScript variable to PHP using AJAX but get 'Undefined index'
如果你認為這可能是重復的我會道歉但我已經嘗試了所有我遇到的問題並且問題仍然存在 - 這讓我很生氣!
我基本上想要在命中鍵時將JS變量傳遞給PHP變量。
這是我的PHP文件設置的簡化版本(位於http://localhost/quiz/index.php
)
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<head>
<body>
<p>
<?php
$uid = $_POST['userID'];
echo $uid;
?>
</p>
<script src="js/site.js"></script>
</body>
</html>
然后在site.js文件中我有以下內容:
jQuery(document).ready(function($) {
$(document.body)
.keyup(function() {
var userID = "Jim";
$.ajax({
type: "POST",
url: 'http://localhost/quiz/index.php',
data: { userID : userID },
success: function(data)
{
alert("success!");
}
});
});
});
當然,我想要在按下某個鍵時在段落中輸出JS變量userID值('Jim'),但它只顯示:
Notice: Undefined index: userID in C:\xampp\htdocs\quiz\index.php on line 66
但是,按下某個鍵時會彈出“成功”警告。
有誰知道我在哪里出錯? 我正在使用Xampp,如果那是相關的!
謝謝!
您需要兩個PHP文件(或一個具有一些分支邏輯的文件)。
您收到錯誤是因為在POST請求中未提交userID
以加載初始頁面。
然后,您需要修改JavaScript,以便它可以使用data
而不僅僅是警報。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.