PHP在ajax调用中显示脚本的响应

时间:2016-12-26 16:01:31

标签: javascript php jquery ajax

我对我的脚本执行ajax调用以上传文件,现在我想显示某些检查的反馈,比如该文件是否已存在。

我无法让它显示我的脚本的响应。为什么答案没有显示?

这是我的ajax电话:

$(document).ready(function()
{
    $("#upload").submit(function(e)
    {
        e.preventDefault();

        $.ajax(
        {
            url: "upload.php",
            type: "POST",
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            success: function(data)
            {
                //i want response here true or false
                location.reload(true);
            }
        });
    });
});

upload.php 脚本:

<?php

$dir = 'files';

echo upload();

/**
 * Upload a file
 *
 * @return bool
 */
function upload()
{
    // Storing source path of the file in a variable
    $sourcePath = $_FILES['file']['tmp_name'];

    // Target path where file is to be stored
    $targetPath = "files/".$_FILES['file']['name'];

    // Check if file already exists
    if (file_exists($_FILES['file']['name'])) {
        return false;
    }

    // Moving Uploaded file
    move_uploaded_file($sourcePath,$targetPath) ;

    return true;
}

1 个答案:

答案 0 :(得分:2)

起初,php的回报是针对内部的东西。您需要回显一个字符串以将值返回给js:

promises = [
  this.methodA().then(wasOk =>
    this.methodB().then(wasOk =>
      this.methodC()
    )
  ),
  this.methodD()
];

你需要一个简单的if在js中检查它:

<?php
 echo "true";
?>

完整代码:

if(data=="true"){
  window.location.reload();
 }