简体   繁体   English

即使成功调用,Ajax调用也总是返回错误

[英]Ajax call always returns error even on successful call

I'm trying to get the hang of Ajax calls and I'm struggling with a basic peace of code :) 我试图摆脱Ajax调用的束缚,并且我在基本的代码和平中苦苦挣扎:)

I keep getting the error alert even when the call seems to be successful. 即使通话似乎成功,我仍会收到错误警报。 I tried to debug the code and added some breakpoints and noticed that done-function does execute. 我尝试调试代码并添加了一些断点,并注意到完成功能确实可以执行。 The form-info has been written away and a string is returned from the php-script. 表单信息已被注销,并且php脚本返回了一个字符串。 For a brief while the text does appear but then disapears after the done-function. 一会儿,文本确实出现了,但是在完成功能之后消失了。 While debugging i don't get the error message. 在调试时,我没有收到错误消息。 It only appears while running the script normally. 它仅在正常运行脚本时出现。

Any help would be greatly appreciated. 任何帮助将不胜感激。

<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 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);

?>

Instead of alerting you might try to use console.log. 您可能会尝试使用console.log而不是发出警报。 You might also add parameters to the faile function to see what comes from the server 您还可以将参数添加到faile函数,以查看来自服务器的内容

funcation fail( jqXHR, textStatus, errorThrown ) {
    console.log("textStatus: " + textStatus);
    console.log("errorThrown: " + errorThrown);
}

I doubt whether you have written your field names and table name correctly 我怀疑您是否正确输入了字段名和表名

INSERT INTO db(Titel, Componist, Link, Description)

Spellings are wrong in title, and you are inserting data not into the table, you insert them into db. 拼写错误的标题是错误的,并且您未将数据插入表中,而是将其插入数据库中。 This is wrong. 错了 Add your table name 添加表格名称

After trying a lot of different things this seems to work: 在尝试了许多不同的方法之后,这似乎可行:

I've added the action attribute to my form tag 我已将动作属性添加到表单标签中

<form method="post" id="form" action="test.php">

And added preventDefault() on the form and changed the error handling 并在表单上添加了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>

So why is the action attribute necessary for this to work? 那么,为什么必须要有action属性才能起作用?

Try the following snippet using success and error callbacks rather than done and fail`. 使用successerror回调而不是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM