我的问题是我无法弄清楚正确的语法(以前从未使用过JSON),无论是在js还是PHP方面,但我认为一旦我弄清楚了js,我就可以自己弄清楚PHP方面。
逻辑目标:发送存储变量 id# 和常量字符串 'del' 的 JSON 数据,接收包含成功/错误信息的 JSON 数据,然后根据成功/错误,将结果回显到不同的 html 中。我最感兴趣的是学习发送和处理收到的json的javascript代码,我认为PHP处理应该更直接,可以自己弄清楚(希望如此)。
编辑 - 当我说成功/错误时,我希望在PHP代码中确定,而不是真正的硬错误。 因此,也许最好将其视为jQuery的回调函数部分中的if
语句。
$(".admin_ru_delete_button").click(function() { //this code is not working
id = ($(this).attr("id"));
dataJson = { "id":id, "type":"del" };
$.post(
'ajax/justPosted_AJAX.php',
dataJson,
function(data){
//$("#admin_errors").html('');
//$("#admin_success").html('');
}
, "json");
return false;
});
非常感谢您的时间/帮助!
数据从javascript对象转换为POST变量 - JSON与此无关(除了PHP -> JS部分)。
if (!empty($_POST['id'])) {
if (!empty($_POST['type'])) {
echo json_encode(array('success' => true, 'id' => $_POST['id']));
} else {
echo json_encode(array('success' => false, 'error' => 'type missing'));
}
} else {
echo json_encode(array('success' => false, 'error' => 'id missing'));
}
以及在您的回调中(当您指定内容类型"json"时,它会自动转换为对象):
function(data){
if (data.success) {
alert('Yay! The ID I sent was ' + data.id);
} else {
alert(data.error);
}
}
如果您希望在未返回 JSON 时出现错误,可以使用$.ajax
:
$.ajax(
'ajax/justPosted_AJAX.php',
{
dataType: 'json',
data: dataJson,
success: function(data){
if (data.success) {
alert('Yay! The ID I sent was ' + data.id);
} else {
alert(data.error);
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('The AJAX call failed: ' + textStatus + ' / ' + errorThrown);
}
}
);
你可以试试:
爪哇语
$(".admin_ru_delete_button").click(function() {
id = ($(this).attr("id"));
$.ajax(
type: "POST",
dataType: "JSON",
url: 'ajax/justPosted_AJAX.php',
data: { "id":id, "type":"del" },
success: function(data){
$("#admin_success").html(data[1] +" "+ data[2]);
}
error: function(data){
console.Log("Error in ajax");
});
return false;
});
这是假设您使用 json_encode($array)
从 PHP 返回 JSONObject/JSONArray 。