-1
假設一個輸入框,例如:爲什麼ajax無法按預期工作?
<input type="text" name="userInput" id="searchTxt" maxlength="50" size="50" onkeydown="return answer(event)">
和一個功能answer(e)
這樣:
function answer(e) {
if (e.keyCode == 13) {
addText();
$.ajax({
method: "POST",
url:"tdat.php",
data: {
userInput:document.getElementById("searchTxt").value,
}
})
document.getElementById("searchTxt").value = ""
}
}
我有一個PHP腳本,內容如下:
<?php
if(isset($_POST['userInput'])){
$userResponse = $_POST['userInput'];
$userResponse = strtoupper($userResponse);
switch($userResponse){
case "NO":
echo "alert(\"NOH.\")";
break;
case "YES":
echo "alert(\"YEAH!!!\")";
break;
default:
echo "alert(\"HAHAHAHAHA. Didn't get that.\")";
}
}
?>
Theoratically如果用戶輸入「yes」,ajax會發送給服務器,PHP應該返回「YEAH!」,但是不管輸入什麼,它都會返回「NOH!」。如果我輸入no,它會提醒「NOH!」,但是當我輸入yes或甚至是lol時,它會提醒「NOH!」。以及。
爲什麼?
我沒有看到你從你的AJAX調用返回任何東西。 –
嘗試在js以及php腳本中打印userInput,並查看您獲得的信息 –
'userInput:userResponse' < - 其中是否設置了userResponse? – WillardSolutions