jQuery Ajax JSON没有返回任何响应

时间:2015-09-03 08:54:10

标签: javascript php jquery ajax json

我有一个简单的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 =&gt; 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 Image问题是JSON。但是,如果我返回JSON值,为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

试试这个:

success: function(data) {
        foobar(data);
    },

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