[英]AJAX and HTML element not working
我試圖設置一個div標簽,以在數據庫中找不到用戶時顯示一條消息。
這是我無法開始的工作:
$("message").html(msg);
如果您能幫助我了解我在做什么錯,那將會有所幫助。 謝謝
$(document).ready(function(){
$("#submit").click(function(){
var username = $("#username").val();
var code = $("#code").val();
var msg = "Who are you?!";
var dataString = 'username='+ username + '&code='+ code;
localStorage.setItem("number",code);
if(username==''||code=='')
{
alert("Um..you are missing something...");
}
else
{
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
cache: false,
success: function(result){
if(result != 0)
alert(result);
},
error: function(){
$("message").html(msg);
}
});
}
return false;
});
});
我的PHP代碼
<?php
$username = trim($_POST["username"]);
$code = trim($_POST["code"]);
include_once './inc/config.php';
$con = new mysqli(HOST, USER, PASSWORD, DATABASE);
$sql="SELECT * FROM info WHERE First_Name='".$username."' AND Line_Number='".$code."'" ;
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
if($num_rows != 0){
echo true;
}
else{
//echo "Who are you?!";
return false;
}
mysqli_free_result($result);
mysqli_close($con);
如果您的消息元素具有ID message
,請像這樣選擇它:
$("#message").html(msg);
如果它具有類 message
,請像這樣選擇它:
$(".message").html(msg);
JQuery文檔包含所有選擇器類型的概述和深入描述。
另外,要觸發Javascript中的error方法,服務器端代碼需要發送HTTP錯誤代碼,例如:
header("HTTP/1.1 404 Not Found");
或像這樣:
http_response_code(404);
要使用ID消息定位div,請使用
$("#message")
您錯過了#
嘗試這個:
$.ajax({...
success: function(data){
if(data)
$("#message").html (msg);
else
alert(data);
}
});
message
是類還是ID? 確保使用正確的選擇器在其上顯示輸出。
error: function(){
$("message").html(msg);
}
當找不到用戶時,是否以404或2xx以外的其他方式響應? 而且,是的,選擇器不正確。 僅在請求服務器期間HTTP錯誤的情況下才會調用您的函數。
這個
else{
//echo "Who are you?!";
return false;
}
不會運行您的功能。 這個
else{
//echo "Who are you?!";
header("HTTP/1.0 404 Not Found");
exit;
}
可以做到,但不是很好的解決方案。 最好的辦法就是退回這樣的東西
$response = array('status' => 'failed', 'text' => 'Whatever');
header('Content-type: application/json');
echo json_encode($response);
exit;
然后在成功功能中處理數據,檢查“狀態”,依此類推。
將#用作ID和。 對於類錯誤:function(){$(“#message”)。html(msg);
除了message
選擇器中明顯的錯誤外,我可以看到的另一個問題是您的代碼在您的PHP中。
您的php代碼不會返回錯誤條件,而是返回true或false,因此始終會調用成功回調。
所以
if($num_rows != 0){
echo true;
}
else{
//echo "Who are you?!";
echo false;
}
然后
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
cache: false,
success: function (result) {
if (result) {
alert(result);
} else {
alert(msg);
//make sure you use a proper selector here
$("message").html(msg);
}
},
error: function () {
$("message").html(msg);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.