Php with AJAX Post - Return values JSON


Php with AJAX Post - Return values JSON

我正在尝试从与AJAX Post交互的php中获取值。我已经读到我应该使用 JSON 数据类型,但这是我第一次这样做,我得到"语法错误:JSON.parse:JSON 数据第 1 行第 72 列 JSON 数据后意外的非空格字符"。

我的 AJAX 如下:

function apfaddpost() {
        var fd = new FormData($('#msform')[0]);
        fd.append( "main_image", $('#main_image')[0].files[0]);
        fd.append( "action", 'apf_addpost');
        $('#form-container').hide();
        $('#processing').show();
        var postProject = $.ajax({
            type: 'POST',
            url: apfajax.ajaxurl,
            data: fd,
            dataType: 'json', 
            processData: false,
            contentType: false,
        });
        postProject.done(function(data, textStatus, XMLHttpRequest) {
                $('#processing').hide();
                $('#confirm').show();
                //elements where I should display success message and link
                var success = '#success';
                var projectlink = '#projectlink';
                jQuery(success).html('');
                jQuery(success).append(data.success);
                $("#projectlink").attr("href", data.projectlink);
        });
        postProject.fail(function(MLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
        });
    }

我的php

if ( $pid != 0 )
    {   
        $message = 'Your post has been successfully added!';
        $project_link = get_permalink($pid);
        $result = array('success'=>$message,'projectlink'=>$projectlink);
        echo json_encode($result);
    }
    else {
        $message = 'Error occurred while adding the post';
        $result = array('fail'=>$message);
        echo json_encode($result);
    }

我的 HTML 应该在哪里打印这些值是:

<div id="confirm" class="row" style="display:none">
        <div class="col-sm-12">
            <h2 class="text-center"><?php _e("Thank you!","KleeiaDev") ?></h2>
            <div class="text-center">
                <p id="success"></p><!-- Here should go the success message -->
                <p>
                    <a id="projectlink" href="">Link</a><!-- Here should go the link I'm getting as result -->
                </p>
            </div>
        </div>
    </div>

我错在哪里?

如果你的 PHP 在echo json_encode($result);后输出其他东西,则会导致该错误。

确保没有其他输出。如果json_encode后没有更多的应用程序逻辑,请使用exit .