PHP没有从jQuery接收JSON数据

时间:2014-02-25 13:15:54

标签: php jquery json

我正在尝试在我的网站中使用ajaxFIleUpload。我没有收到JavaScript发送给PHP的JSON数据。我被困在这一点上。文件上传是好的,但我无法收到任何帖子值。我的jQuery函数是

$(function() {

    $(document).on("submit", "#upload_file", function(e) {

        e.preventDefault();

        $.ajaxFileUpload({
            url             :base_url + 'payments/uploadPaymentSlip/',
            secureuri       :false,
            fileElementId   :'userfile',
            type        : 'POST',
            data: { paymentFormInputAmount: 'asdasd' },
            success : function (data, status)
            {
                if(data.status != 'error')
                {
                    $('#files').html('<p>Reloading files...</p>');
                    //refresh_files();
                    $('#files').val('');
                }
                alert(data.msg);
            },
           dataType: 'json'
        });

    });
});

我的PHP函数是

function uploadPaymentSlip() {
    $status = "";
    $msg = "";
    $file_element_name = 'userfile';

    $status = "error";
    // checking whether json value shows in php or not
    // $_POST['paymentFormInputAmount'] is also not working
    $msg = $_POST['paymentFormInputAmount'];

    if ($status != "error") {
        $config['upload_path'] = realpath( APPPATH . '../uploads/paymentSlip' );
        $config['allowed_types'] = 'gif|jpg|png|doc|txt';
        $config['max_size'] = 1024 * 8;
        $config['encrypt_name'] = TRUE;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload($file_element_name)) {
            $status = 'error';
            $msg = $this->upload->display_errors('', '');
        }
        else {
            $data = $this->upload->data();
            // $file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
            if($file_id) {
                $status = "success";
                $msg = "File successfully uploaded";
            }
            else {
                unlink($data['full_path']);
                $status = "error";
                $msg = "Something went wrong when saving the file, please try again.";
            }
        }
        @unlink($_FILES[$file_element_name]);
    }

    echo json_encode(array('status' => $status, 'msg' => $msg));
}

1 个答案:

答案 0 :(得分:1)

type: 'json'必须为type: 'POST'

你应该添加:

contentType: 'json',
dataType: 'json'

作为$.ajaxFileUpload

的参数

contentType表示您将数据发送为json

dataType表示您期望结果为json.

的类型