图片通过ajax提交

时间:2018-07-26 22:55:40

标签: javascript php 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调用管理图像上传,因为在我尝试提交而无需重新加载页面之前,我不理解原始表单为何工作正常。 (请注意,我知道表已经过时了,一旦核心进程正常工作,它们就会被删除)

1 个答案:

答案 0 :(得分:0)

第一件事是,未显示“序列化”数据的原因是,您未序列化为表单数据,而是序列化到了按钮。如果您要序列化工作,可以尝试这种方式

$(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 ...'); 
      });

   })
})

Check it js fiddle 希望对您有帮助