0

My problem basically is that I cannot figure out the proper syntax (never used JSON before), both on the js and PHP side but I think I can figure the PHP side out myself once I figure out the js.

Logical goal: send JSON data storing variable id# and constant string 'del' , receive JSON data that is contains success/error information, and then based on success/error, echo results into different html. I am most interested in learning the javascript code on sending and processing received json, I think the PHP handling should be more straightforward to figure out on my own (hopefully).

edit -- when i say success/error, i want that to be determined in the PHP code and not a TRUE hard error. so maybe it's better to think of it as just, an if statement in the callback function portion of the jQuery.

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

Thanks a lot for your time/help!

4

2 回答 2

1

数据从 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);
        }
    }
);
于 2013-11-08T19:40:07.260 回答
0

你可以试试:

Javascript

$(".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).

于 2013-11-08T19:42:01.977 回答