Ajax 调用 PHP 没有成功返回


Ajax call to PHP not returning succesfull

这里的问题是我的Ajax调用失败了。 alert(RealMessage);被调用,所以我知道输入了这个函数,但没有调用"MSG SENT"警报,这告诉我这个 Ajax 请求失败了。我认为 PHP 请求返回成功是脚本运行。即使认为我没有返回任何东西,我是否需要以某种方式回显一些东西以表明它是成功的?

.JS:

$("#EnteredMessage").submit(function(){
    var RealMessage = document.getElementById("message").value;
    alert(RealMessage);
    $.ajax({
        url:"sendmessage.php",
        data: {msg:RealMessage},
        type:"POST",
        datatype: "JSON",
        success: function(){
            console.log("Message sent");
            alert("MSG SENT");
        }
    });
});

.PHP:

<?php
$message = $_POST["msg"];
$filecreate = fopen("messages.txt","w");
fwrite($filecreate,$message);
fclose($filecreate);

在 PHP 中,用 json_encode 回显结果

<?php
$message = $_POST["msg"];
$filecreate = fopen("messages.txt","w");
fwrite($filecreate,$message);
fclose($filecreate);
echo json_encode(array("result"=>"your result"));

在你的jQuery代码中datatype是一个不正确的关键字。 dataType 是正确的关键字,并用引号将keys括在data中,然后在 ajax 成功控制台中.log返回data_result

$("#EnteredMessage").submit(function(){
    var RealMessage = document.getElementById("message").value;
    alert(RealMessage);
    $.ajax({
        url:"sendmessage.php",
        data: {'msg':RealMessage},
        type:"POST",
        dataType: "json",
        success: function(data_result){
            console.log(data_result);
        }
    });
});

试试这个

使用json_encode json_encode

echo json_encode(array("status"=>'success'));

是的,您需要通过 echo 返回一些 json 响应,请参阅下面的代码。

在 php 中

<?php
$message = $_POST["msg"];
$filecreate = fopen("messages.txt","w");
fwrite($filecreate,$message);
fclose($filecreate);
echo json_encode(array("result"=>'Message sent!!!'));  //you can sent any thing
?>