我有一个简单的 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 脚本正在控制台中被取消...
我认为问题出在 JSON 上。但如果我返回 JSON 值,为什么会发生这种情况?
最佳答案
试试这个:
success: function(data) {
foobar(data);
},
//Place outside insertInto
function foobar(data) {
if(data){
alert("Successfully added!")
} else {
alert ("else!")
}
}
关于javascript - jQuery Ajax JSON 不返回任何响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32371135/