[英]Ajax call always returns error even on successful call
我試圖擺脫Ajax調用的束縛,並且我在基本的代碼和平中苦苦掙扎:)
即使通話似乎成功,我仍會收到錯誤警報。 我嘗試調試代碼並添加了一些斷點,並注意到完成功能確實可以執行。 表單信息已被注銷,並且php腳本返回了一個字符串。 一會兒,文本確實出現了,但是在完成功能之后消失了。 在調試時,我沒有收到錯誤消息。 它僅在正常運行腳本時出現。
任何幫助將不勝感激。
<div id="formDiv">
<form method="post" id="form">
<label for="title">Title: </label>
<input type="text" name="title" id="title" />
<label for="composer">Composer: </label>
<input type="text" name="composer" id="composer" />
<label for="link">Link: </label>
<input type="text" name="link" id="link" />
<label for="description">Description: </label>
<input type="text" name="description" id="description" />
<input type="submit">
</div>
<div id="outerDiv">
<p id="p"></p>
</div>
<script>
$("#form").submit(function(){
var postData = $(this).serializeArray();
$.ajax({
url: "test.php",
type: "POST",
data: postData,
dataType: "text"
})
.done(function(data){
$("#p").text(data);
})
.fail(function(){
alert("Error!");
});
});
</script>
test.php
<?php
$dbc = mysqli_connect('localhost', 'root', '', 'db');
if ($dbc->connect_error) {
die('Connect Error: ' . $dbc->connect_error);
}
$title = $_POST['title'];
$composer = $_POST['composer'];
$link = $_POST['link'];
$description= $_POST['description'];
$query = "INSERT INTO table(Titel, Componist, Link, Description) VALUES ('$title', '$composer', '$link', '$description')";
mysqli_query($dbc, $query);
$resultquery = mysqli_query($dbc,"SELECT * FROM table");
$result = "";
while($row = mysqli_fetch_assoc($resultquery)){
$result .= $row["Titel"]." | ".$row["Componist"]." | ".$row["Link"]." | ".$row["Description"]."\n";
}
echo $result;
mysqli_close($dbc);
?>
您可能會嘗試使用console.log而不是發出警報。 您還可以將參數添加到faile函數,以查看來自服務器的內容
funcation fail( jqXHR, textStatus, errorThrown ) {
console.log("textStatus: " + textStatus);
console.log("errorThrown: " + errorThrown);
}
我懷疑您是否正確輸入了字段名和表名
INSERT INTO db(Titel, Componist, Link, Description)
拼寫錯誤的標題是錯誤的,並且您未將數據插入表中,而是將其插入數據庫中。 錯了 添加表格名稱
在嘗試了許多不同的方法之后,這似乎可行:
我已將動作屬性添加到表單標簽中
<form method="post" id="form" action="test.php">
並在表單上添加了preventDefault()並更改了錯誤處理
<script>
$("#form").submit(function(e){
var postData = $(this).serializeArray();
$.ajax({
url: "test.php",
type: "POST",
data: postData,
dataType: "text"
})
.error(function( jqXHR, textStatus, errorThrown ) { console.log(errorThrown); })
.done(function(data){
$("#p").text(data);
})
e.preventDefault();
});
</script>
那么,為什么必須要有action屬性才能起作用?
使用success
和error
回調而不是done
和失敗`,嘗試以下代碼段。
$("#form").submit(function(){
var postData = $(this).serialize();
$.ajax({
url: "test.php",
type: "POST",
data: postData,
dataType: "text",
success: function(data){
$('#p').text(data);
},
error: function(){
alert("Error!");
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.