认为我的 ajax 出了点问题


Think something's wrong with my ajax?

当我

通过http POST请求发送表单值时,我要做的是返回"addTemplate.php"的echo值。但是,当我发送请求时,绝对没有任何反应。

我该怎么办?

这是我的 JS

$(document).ready(function() {
    $("#sendTemplate").on("submit", function(event) {
        var template = $("#template").val();
        event.preventDefault();
        $.ajax({method: "POST", url: "addTemplate.php", data: template, success: function(result) {
            alert(result);
        });
    });
});

这是我的网页

<!DOCTYPE html>
<html>
    <head>
        <title>Admin</title>
        <link type="text/css" rel="stylesheet" href="stylesheet.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script src="adminscript.js"></script>
    </head>
    <body>
        <h1>Admin/Developer page</h1>
        <form id="sendTemplate">
            <p>Enter a new template for the server: (Enter #word to enter a placeholder for words)</p><input type="text" name="template" id="template">
            <input type="submit" name="submit">
        </form>
        <div id='success'></div>
        <br><br><br><br>
        <form action="turing.html">
            <button type="submit">Home</button>
        </form>
    </body>
</html>

这是我的 php

$template = $_POST["template"]; 
if(strlen($template) <= 100 && strpos($template, "#word")) {
    file_put_contents("templates.txt", "'r'n" . $template, FILE_APPEND);
    header("Location: http://community.dur.ac.uk/h.j.g.baum/admin.html");
    echo "True";
}
else {
    echo "False";
}

我的代码(很可能在 JavaScript 中)出了什么问题,我该如何改进它?

谢谢

替换 ajax 数据:

data: template,

跟:

data: "template="+template,

问题:

您正在使用 $_POST['template'] 来获取值,并且没有在 ajax 数据中定义。

我认为你缺少Ajax成功函数的结束卷曲

$(document).ready(function() {
    $("#sendTemplate").on("submit", function(event) {
        var template = $("#template").val();
        event.preventDefault();
        $.ajax({method: "POST", url: "addTemplate.php", data: template, success: function(result) {
            alert(result);
        }});
    });
});

id 这样做:

 $(document).ready(function () {
            $("#sendTemplate").on("submit", function () {
                $.ajax({
                    method: "POST",
                    url: "addTemplate.php",
                    data: $(this).serialize(),
                    success: function (result) {
                        alert(result);
                    });
                return false;
            });
        });

只需将 js 更改为

$(document).ready(function() {
$("#sendTemplate").on("submit", function(event) {
    var template = $("#sendTemplate").serialize();
    $.ajax({method: "POST", url: "test.php", data: template, success: function(result) {
        alert(result);
    }});
    event.preventDefault();
});

<form id="sendTemplate">

<form id="sendTemplate" method="POST">

这是获取表单数据并将其传递给 php 脚本的正确方法