duanlu1959 2015-09-03 08:54
浏览 235

jQuery Ajax JSON没有返回任何Response

I have a simple Ajax function:

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

In insert.php if I do:

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

$data =  ['status'=>'Ok'];

return json_encode($data);

?>

I get success and I get the Response {Status => Ok}

If I do:

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

?>

I get the response but I get the error function.(the data is inserted).

And If I do:

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

?>

The data is inserted, but I don't get the response and my insert.php script is being cancelled in the console...

I Image the problem Is with JSON. But why is this happening if I am returning the JSON values?

  • 写回答

1条回答 默认 最新

  • drsl90685154 2015-09-03 10:08
    关注

    Try this:

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog