weixin_33670713 2016-10-15 18:36 采纳率: 0%
浏览 50

PHP echo jQuery AJAX请求

This is my jQuery request to upload an image file

$('#upload-image').change(function(e){
    var file = e.target.files[0];
    var imageType = /image.*/;
    if (!file.type.match(imageType))
        return;
    console.log(file);
    var form_data = new FormData();
    form_data.append('file', file);
    console.log(form_data);
    $.ajax({
        url: 'http://localhost/upload.php',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'POST',
        success: function(response){
            console.log(response);
        },
        error: function(error){
            console.log(error);
        }
    });
});

This is upload.php on local webserver

<?php
    header('Access-Control-Allow-Origin: *');
    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
        $target_path = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . $_FILES['file']['name'];
        echo $target_path;
    }
?>

When I upload the image and send request. It returns and logs for me complete code lines of upload.php, not the result from echo command line that I want. I check console Network tab and see that the response is nothing except complete code of upload.php. It truly does not handle anything server-side. What did I do wrong?

  • 写回答

1条回答 默认 最新

  • weixin_33716154 2016-10-15 18:58
    关注

    You need to make sure that PHP runs server-side. If there's no PHP handler installed, the server will return the content of your upload.php file as text. I think that's your primary problem.

    Based on your platform, you may try:

    First of all make sure your PHP works, by creating a file called info.php in your webroot folder with the following content

    <?php
    phpinfo();
    

    This should display your configuration. Then you can start debugging the Javascript. The content type should by multipart/form-data so that the server knows it expects an upload.

    Good luck!

    评论

报告相同问题?

悬赏问题

  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器