php - PHP中的Json解码

标签 php javascript jquery json

我正在尝试解码我​​在 javascript (jquery) 中使用 ajax 调用发送的 php 中的 JSON。

JavaScript 代码:

    var editSchedule_data = {
        'action'            : 'editSchedule',
        'eventid'           : $('#eventid').val(),
        'pixels_per_minute' :$('#pixels_per_minute').val(),
         artists: {
            artist: []
        }
    }

    $('.artist').each(function(index) {
        var id=$(this).attr('id');
        id=id.split('_');
        editSchedule_data.artists.artist.push({
            'artistid'    : id[0],
            'stageid'     : id[1],
            'left'        : $(this).offset().left-$('.artists').offset().left,
            'width'       : $(this).width()
        });
    });

    $.ajax({
        type :   "POST",
        url  :   "callback.php",
        data :   editSchedule_data,
        dataType :   "json",
        async    :   true,
        success   :   function(json)  {
            if(json.success)  {
                showSucces(json.message);

            }
            else{
                showError(json.message);
            }
        },
        error: function(error){
            alert("An error occurred: "+error.message);
        }
    });

PHP 代码:

$clean = sanitize($_POST);

echo(json_encode($clean['artists']),
json_last_error());

echo(json_decode($clean['artists']),
json_last_error());

我的输出: 编码:

{"artist":[{"artistid":"4","stageid":"3","left":"360","width":"240"},{"artistid":"3","stageid":"4","left":"120","width":"240"},{"artistid":"1","stageid":"5","left":"120","width":"180"},{"artistid":"2","stageid":"5","left":"300","width":"120"},{"artistid":"5","stageid":"6","left":"480","width":"120"}]}
0

解码:

0

谁能告诉我如何使解码功能正常工作?

最佳答案

你为什么要在那里使用 json_decode?您已经在 $_POST 中将数据作为数组。这就是为什么 json_decode 失败并返回 NULL 的原因……它需要一个格式正确的字符串,而您正在向它传递一个数组。 如果 dataType : "json"参数让您感到困惑,它指定您期望从服务器返回的数据类型,而不是您发送的数据类型。 您应该简单地处理来自 $_POST 的数据,创建您的响应,对其应用 json_encode 并回显结果字符串。

关于php - PHP中的Json解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4041221/

相关文章:

php - 如何使用 PHP 按钮删除 MySql 数据库行

php - 在表单提交后提供下载服务

javascript - 更改 DOM 元素的 insideText 是否会导致新的布局计算/渲染?

javascript - 取消选择滚动开始时的所有 ListView 元素

javascript - 带有点击事件的 stopPropagation()

javascript - HTML 类未删除

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php json 请求 : json_decode unicode string

javascript - 如何更改 Facebook 登录按钮的样式?

javascript - 警告 : validateDOMNesting(…): <form> cannot appear as a descendant of <form> by using semantic-ui-react modal