【问题标题】:Ajax image upload failure, Script doesn't get the php isset functionAjax图片上传失败,脚本获取不到php isset函数
【发布时间】:2016-11-13 20:24:11
【问题描述】:

我一直在关注一些 ajax 上传教程,它工作正常。

这就是我的做法, 我像这样在 html 中创建了一个表单。

 <form id="submit_form" action="php-script/test_lates_statusbx-script.php" method="post" enctype="multipart/form-data">  
                     <div class="form-group">  
                          <label>Select Image</label>  
                          <input type="file" name="ui-is-status_is_photo_fl" id="image_file" />  
                          <textarea name="status_is_text_ara"></textarea>
                          <span class="help-block">Allowed File Type - jpg, jpeg, png, gif</span>  
                     </div>  
                     <input type="submit" name="is_status_forum_btn" class="btn btn-info" value="Upload" />  
                </form>  
<div id="image_preview">  
            </div>

这是我的 ajax 代码,

 $(document).ready(function(){  
      $('#submit_form').on('submit', function(e){  
           e.preventDefault();  
           $.ajax({  
                url:"php-script/test_lates_statusbx-script.php",  
                method:"POST",  
                data:new FormData(this),  
                contentType:false,  
                //cache:false,  
                processData:false,  
                success:function(data)  
                {  
                     $('#image_preview').html(data);  
                     $('#image_file').val('');  
                }  
           })  
      });  
      
 }); 

我的 php 看起来像这样,

if(isset($_POST['is_status_forum_btn'])){
    echo $fileactuname = basename($_FILES['ui-is-status_is_photo_fl']['name']);
    echo $textareastatus = htmlspecialchars($_POST['status_is_text_ara']);
}

问题:当我单击提交按钮时,它不会执行我的代码。但是,如果我在 isset 函数之外回显某些内容,我会错在哪里?

【问题讨论】:

  • 在您的 php 脚本中 if 之前的条件放入 print_r($_POST); 并检查您在 POST 变量中获得的参数以及您在 isset 中检查的所需参数是否可用
  • @Haridarshan 如果我在 isset 函数中回显它,我什么也得不到
  • 为什么你在 isset 条件下做 echo。在isset 条件外打印$_POST 并显示您得到的输出
  • @Haridarshan 我的整个网站文件上传现在不适用于 jquery。你有什么解决办法吗?
  • 由于您是通过客户端脚本自己发送表单数据,因此提交按钮值不会成为提交内容的一部分 - 因此您检查提交按钮值是否已发送失败。

标签: php ajax


【解决方案1】:

提交按钮只有用于提交表单才是成功的控件。

你是:

  1. 使用提交按钮提交表单
  2. 防止提交事件的默认行为使表单不被提交
  3. 使用 JavaScript 从表单中收集数据
  4. 使用该数据发出 HTTP 请求

由于(由于第 2 步)提交按钮不再用于提交表单,因此它不包含在您使用 FormData() 创建的对象中。

测试您正在发送的另一条数据是否存在

例如

if(isset($_FILES['ui-is-status_is_photo_fl'])) 

【讨论】:

    【解决方案2】:

    在你的 php 脚本中,像这样尝试

    if  (
        isset($_FILES['ui-is-status_is_photo_fl']['name']) && 
        $_FILES['ui-is-status_is_photo_fl']['error'] == 0
    ) {
        print_r($_FILES);
        print_r($_POST);
        // Do the required task here
    } else {
        echo "error";
    }
    

    【讨论】:

    • 我找到了答案,还是谢谢你!
    猜你喜欢
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    相关资源
    最近更新 更多