index.php中的代码:
<!DOCTYPE html>
<html lang="en-us" dir="ltr">
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$( ".trashitem" ).click(function(e) {
e.preventDefault();
var trashlink = $(this);
var res = confirm("Are you sure you want to trash the selected item?");
if ( res != false ) {
var trashurl = trashlink.attr("href");
var trashid = trashlink.data("id");
$.ajax({
url: trashurl,
type: "POST",
data: { "trashid": trashid },
datatype: "json",
success: function(response) {
console.log(response); // Output: {"success":true,"error":false}
console.log(response.success); // Output: undefined
if (response.success == true) {
trashlink.parents("li").fadeOut(300, function() {
trashlink.parents("li").remove();
});
}
}
});
}
});
});
</script>
</head>
<body>
<ul>
<li><a class="trashitem text-color-alert" href="trash.php" data-id="20">Trash</a></li>
<li>This is undeletable item.</li>
</ul>
</body>
</html>
trash.php中的代码是:
<?php
$id = $_POST['trashid'];
$error = false;
$success = false;
if ($id) {
$success = trash_post($id);
$response = array(
'success' => $success,
'error' => $error
);
}
echo json_encode( $response );
function trash_post( $target_id ) {
return true;
}
请查看index.php中的第一个代码段,其中:
console.log(response); // Output: {"success":true,"error":false}
但是当我想访问success
时:
console.log(response.success); // undefined
为什么它会给我undefined
而不是true
?我在Stackoverflow上发现了一些类似于我的帖子,但它们对我没用。
答案 0 :(得分:1)
可能<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Yamaha 125 RR</td>
<td>PJ/1010/2015</td>
<td>2015-11-18</td>
<td>2015-11-20</td>
<td id="this-is-empty"></td>
<td>Gear 1</td>
<td>10</td>
<td>action</td>
</tr>
</table>
只是一个字符串,但不是response
试
Object
或尝试在var a = JSON.parse(response);
console.log(a.success);
文件
php
这个集合是php文件的内容类型header('Content-Type: application/json');
答案 1 :(得分:1)
尝试使用此
response['success'] == true
而不是
response.success == true
答案 2 :(得分:0)
尽量不要为响应使用成功或错误标志,而是使用状态代码并构建正确的响应。您可以使用http_response_code()
函数来执行此操作。例如:
<?php
http_response_code(200);
?>
然后要正确处理你的ajax调用中的响应,请执行以下操作:
$.ajax({
url: trashurl,
type: "POST",
data: { "trashid": trashid },
datatype: "json"
})
.done(function (response) { //response status code is 200
trashlink.parents("li").fadeOut(300, function() {
trashlink.parents("li").remove();
});
})
.fail(function (xh) {
//Handle failed response
});