jQuery Ajax JSON不返回任何响应


jQuery Ajax JSON not returning any Response

我有一个简单的Ajax函数:

insertInto = function(){
    console.log("Hello ");

    var power = $("#power").val();
    var vehicle = $("#vehicle").val();
    var sendData = { "power": power, "vehicle": vehicle };
    $.ajax({
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        url: "http://192.168.15.42//Test/www/insert.php",
        data: sendData,
        success: function(data) {
            if(data){
            alert("Successfully added!")
            } else {
            alert ("else!")
            }
        },
        error: function(data) {
            alert("error")
        }
    });
}

insert.php中如果我这样做:

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$data =  ['status'=>'Ok'];
return json_encode($data);
?>

我得到成功,我得到响应{Status => Ok}

如果我这样做:

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include('connect.php');
$power=$_POST["power"];
$vehicle=$_POST["vehicle"];
$sql = "INSERT INTO practicetbl (power,vehicle) VALUES ('$power' , '$vehicle')";
return json_encode($sql);
?>

我得到了响应,但我得到了错误函数。

如果我这样做了:

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include('connect.php');
$data =  ['status'=>'Ok'];
$power=$_POST["power"];
$vehicle=$_POST["vehicle"];
$sql = "INSERT INTO practicetbl (power,vehicle) VALUES ('$power' , '$vehicle')";
if ($conn->query($sql) === TRUE) {
    $success =  "New record created successfully";
    echo json_encode($success);
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
return json_encode($sql);
?>

数据被插入,但我没有得到响应,我的insert.php脚本在控制台中被取消…

I想象问题是JSON。但如果我返回JSON值,为什么会发生这种情况?

试试这个:

success: function(data) {
        foobar(data);
    },
//Place outside insertInto
function foobar(data) {
  if(data){
    alert("Successfully added!")
  } else {
    alert ("else!")
  }
}