首页 > 解决方案 > 通过ajax提交图片

问题描述

我正在尝试增强网站的后端,以使用户更容易更新产品。我正在将流程移动到交互式工具提示中,以便可以从显示产品的页面执行操作,而不是发送到不同的页面类型以进行小的更改。

不过,我对图像上传部分感到困惑。我正在使用这部分 JS

$(document).ready(function() {
    $(".layout-save").click(function(e){
        e.preventDefault();
        console.log($(this).serialize());
        $.ajax({
            url: 'product_image_ajax.php?action=save',
            type: 'POST',
            data: $(this).serialize(), // it will serialize the form data
            dataType: 'html'
        })
        .done(function(data) {
            //console.log(data);
        })
        .fail(function(){
            alert('Ajax Submit for Image Save Failed ...'); 
        });
    });
});

表格的基础是

<form name="image_define" action="http://localhost/jsc/jscadmin/product_image_ajax.php?&amp;products_filter=310&amp;newImg=1&amp;action=save" method="post" enctype="multipart/form-data"><input type="hidden" name="securityToken" value="149cbe8b85ec27c089b867be283dff2e">
<table border="0" width="100%" cellspacing="0" cellpadding="2">
  <tbody>
    <tr>
      <td class="jscBoxContent">or <input type="text" name="imgNewBaseDir" size="20"></td>
    </tr>
    <tr>
      <td class="jscBoxContent"><br><strong>Base image file</strong>&nbsp;&nbsp;<strong class="errorText">(required)</strong><br>An original image must be defined. The original image is assumed to be the smallest when medium or large images are entered.<br><input type="file" name="default_image" size="20" accept="image/jpeg,image/jpg,image/gif,image/png"><br></td>
    </tr>
    <tr>
      <td align="center" class="jscBoxContent"><br><input type="image" src="includes/languages/english/images/buttons/button_save.gif" border="0" alt="Save" title=" Save " class="layout-save" data-newimg="1">&nbsp; <input id="close-tooltip" type="button" value="Cancel" alt="Cancel" title="Cancel"></td>
    </tr>
  </tbody></table>
</form>

生成此 HTML 的实际 php 是

case 'layout_new':  
                if ( $action != 'layout_edit' ) {
                    $imgNameStr .= ( $no_images ) ? "&amp;newImg=1" : '&amp;imgBase='.$products_image_base
                                                  . "&amp;imgBaseDir=" . $products_image_directory 
                                                  . "&amp;imgExtension=" . $default_extension;
                    $heading[] = array(
                        'text' => '<strong>' . TEXT_INFO_NEW_PHOTO . '</strong>'
                    );
                }

                $contents = array(
                    'form' => zen_draw_form('image_define', FILENAME_PRODUCTS_IMAGE_AJAX, 
                        '&products_filter=' . $products_filter . $imgNameStr
                        . '&amp;action=save', 'post', 'enctype="multipart/form-data"')
                ); //steve check this &products_filter=

                // check if this is a master image or if no images exist
                if ($no_images) {
                    $contents[] = array(
                        'text' => '<strong>' . TEXT_INFO_IMAGE_BASE_NAME . '</strong><br />' 
                    );
                    $contents[] = array(
                        'text' => zen_draw_input_field('imgBase', '', 'size="30"')
                    );

                    $dir = @dir(DIR_FS_CATALOG_IMAGES);
                    $dir_info[] = array('id' => '', 'text' => TEXT_INFO_MAIN_DIR);
                    while ($file = $dir->read()) {
                        if (is_dir(DIR_FS_CATALOG_IMAGES . $file) 
                            && strtoupper($file) != 'CVS' 
                            && $file != "." 
                            && $file != ".." 
                            && $file != 'original' 
                            && $file != 'medium'
                            && $file != 'large') {
                            $dir_info[] = array('id' => $file . '/', 'text' => $file);
                        }
                    }
                    $contents[] = array('
                        text' => '<br /><strong>' . TEXT_INFO_BASE_DIR . '</strong><br />' . TEXT_INFO_NEW_DIR
                    );
                    $contents[] = array(
                        'text' => TEXT_INFO_IMAGE_DIR . zen_draw_pull_down_menu('imgBaseDir', $dir_info, "")
                    );
                    $contents[] = array(
                        'text' => TEXT_INFO_OR.' ' . zen_draw_input_field('imgNewBaseDir', '', 'size="20"') 
                    );
                } else if ($action != 'layout_edit') {
                    $contents[] = array(
                        'text' => '<strong>' . TEXT_INFO_IMAGE_SUFFIX . '</strong><br />' . TEXT_INFO_USE_AUTO_SUFFIX . '<br />' 
                    );
                    $contents[] = array(
                        'text' => zen_draw_input_field('imgSuffix', $selected_image_suffix, 'size="10"') 
                    );
                }

                // -----
                // Set up the "acceptable" file types for the form, depending on whether or not the active product
                // currently has an image defined.
                //
                if ($no_images) {
                    $accept = 'image/jpeg,image/jpg,image/gif,image/png';
                } else {
                    switch (strtolower($products_image_extension)) {
                        case '.gif':
                            $accept = 'image/gif';
                            break;
                        case '.png':
                            $accept = 'image/png';
                            break;
                        case '.jpg':        //-Fall-through ...
                        case '.jpeg':
                            $accept = 'image/jpeg,image/jpg';
                            break;
                        default:
                            $accept = 'image/jpeg,/image/jpg,image/gif,image/png';
                            break;
                    }
                }
                $file_parms = 'accept="' . $accept . '"';

                // Image fields
                if ( $action == 'layout_new' ) {// display warning on edit screen that the default file must be filled in
                    //-------------------------
                    $contents[] = array(
                        'text' => '<br /><strong>' . TEXT_INFO_DEFAULT_IMAGE . '</strong>&nbsp;&nbsp;<strong class="errorText">(required)</strong><br />' 
                            . TEXT_INFO_DEFAULT_IMAGE_HELP . '<br />'
                            . zen_draw_input_field('default_image', '', 'size="20" ' . $file_parms, false, 'file') . '<br />' . $pInfo->products_image
                    );

                } else {
                    $contents[] = array(
                        'text' => '<br /><strong>' . TEXT_INFO_DEFAULT_IMAGE . '</strong><br />' 
                            . TEXT_INFO_DEFAULT_IMAGE_HELP . '<br />'
                            . zen_draw_input_field('default_image', '', 'size="20" '. $file_parms, false, 'file') . '<br />' . $pInfo->products_image
                    );
                }

提交表格时,

console.log($(this).serialize());

是空的,因此图像不会更新。

是否有任何特殊的过程可以通过 AJAX 调用管理图像上传,因为我不明白为什么原始表单可以正常工作,直到我尝试在不重新加载页面的情况下提交。(注意,我知道表格已经过时,一旦核心流程开始工作,它们就会被删除)

标签: javascriptphpajax

解决方案


首先,您的“序列化”数据未显示的原因是,您没有序列化为表单数据,而是序列化为按钮。如果您想序列化工作,可以尝试这种方式

$(document).ready(function(){
   $(".layout-save").click(function(e){
      console.log($('form').serialize())
   })
})

第二件事是您无法仅使用获取文件数据serialize() 您可以尝试这种方式使用ajax发送文件

 $(document).ready(function(){
    let file
   $('input[name="default_image"]').change(function(){
     file = $('input[name="default_image"]').prop('files')[0]

   })
   $(".layout-save").click(function(e){
        let inputvalu = $('input[name="imgNewBaseDir"]').val()
         var form_data = new FormData();
         form_data.append('imgNewBaseDir' , inputvalu )
         if(file)
            form_data.set('default_image' , file , file.name )
        alert(inputvalu)
        $.ajax({
            url: "product_image_ajax.php?action=save",
            type: 'post',
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
        })
        .done(function(data) {
        //console.log(data);
        })
       .fail(function(){
        alert('Ajax Submit for Image Save Failed ...'); 
      });

   })
})

检查它 js fiddle 希望它会帮助你


推荐阅读