jquery.jqGrid.min.js:14未捕获的TypeError:无法读取未定义的属性“0”

时间:2017-03-21 09:03:19

标签: jquery jqgrid


在我的jqgrid形式的应用程序中,我想同时上传文件以及发布数据。我在哪里使用 jquery版本作为jquery-3.1.1.js和jqgrid版本作为5.2.0 的。
正如我在intenet上读到的,它无法同时在jqgrid上传文件和发布数据。因此,在提交文件以外的数据后,您可以通过 ajaxFileUpload 方法上传文件。因为我使用的是最新版本的jquery ,它无法通过此功能上传文件。
所以我的问题是: - 1)上面的错误是什么?如何删除它
2)如何在没有ajaxfile上传的情况下在jqgrid上传文件

提前致谢

1 个答案:

答案 0 :(得分:0)

我尝试通过jqGrid的'afterSubmit'事件使用ajaxfileupload.js,但错误仍然存​​在。否则,我以不同的方式得到它。

我用过:

  • Guriddo jqGrid JS - v5.2
  • 的jqGrid / CSS / ui.jqgrid-bootstrap.css
  • 的jquery-3.1.1.min.js

<强> ajaxFileUpload.js

    jQuery.extend({

    handleError: function( s, xhr, status, e ) {
        // If a local callback was specified, fire it
        if ( s.error ) {
            s.error.call( s.context || window, xhr, status, e );
        }

        // Fire the global callback
        if ( s.global ) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
        }
    },
    createUploadIframe: function(id, uri)
    {
        //create frame
        var frameId = 'jUploadFrame' + id;
        var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
        if(window.ActiveXObject)
        {
            if(typeof uri== 'boolean'){
                iframeHtml += ' src="' + 'javascript:false' + '"';

            }
            else if(typeof uri== 'string'){
                iframeHtml += ' src="' + uri + '"';

            }
        }
        iframeHtml += ' />';
        jQuery(iframeHtml).appendTo(document.body);

        return jQuery('#' + frameId).get(0);
    },
    createUploadForm: function(id, fileElementId, data)
    {
        //create form
        var formId = 'jUploadForm' + id;
        var fileId = 'jUploadFile' + id;
        var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
        if(data)
        {
            for(var i in data)
            {
                jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
            }
        }
        var oldElement = jQuery('#' + fileElementId);
        var newElement = jQuery(oldElement).clone();
        jQuery(oldElement).attr('id', fileId);
        jQuery(oldElement).before(newElement);
        jQuery(oldElement).appendTo(form);

        //set attributes
        jQuery(form).css('position', 'absolute');
        jQuery(form).css('top', '-1200px');
        jQuery(form).css('left', '-1200px');
        jQuery(form).appendTo('body');
        return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout        
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime();
        var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
        var io = jQuery.createUploadIframe(id, s.secureuri);
        var frameId = 'jUploadFrame' + id;
        var formId = 'jUploadForm' + id;
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
        {
            jQuery.event.trigger( "ajaxStart" );
        }
        var requestDone = false;
        // Create the request object
        var xml = {};
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
        {
            var io = document.getElementById(frameId);
            try
            {
                if(io.contentWindow)
                {
                    xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                    xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

                }else if(io.contentDocument)
                {
                    xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                    xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
                }
            }catch(e)
            {
                jQuery.handleError(s, xml, null, e);
            }
            if ( xml || isTimeout == "timeout")
            {
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
                    {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );

                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e)
                {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind();

                setTimeout(function(){
                    try
                    {
                        jQuery(io).remove();
                        jQuery(form).remove();
                        } catch(e){
                        jQuery.handleError(s, xml, null, e);
                    }
                }, 100);
                xml = null
            }
        };
        // Timeout checker
        if ( s.timeout > 0 )
        {
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }

        try
        {
            var form = jQuery('#' + formId);
            jQuery(form).attr('action', s.url);
            jQuery(form).attr('method', 'POST');
            jQuery(form).attr('target', frameId);
            if(form.encoding)
            {
                jQuery(form).attr('encoding', 'multipart/form-data');
            }
            else
            {
                jQuery(form).attr('enctype', 'multipart/form-data');
            }
            jQuery(form).submit();

        } catch(e)
        {
            jQuery.handleError(s, xml, null, e);
        }

        jQuery('#' + frameId).on('load', uploadCallback);
        return {abort: function () {}};

    },
    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();

        return data;
    }
});

因此,我将名为“foto”的字段或列配置为接收将通过上传文件传递的图片。

$("#jqGrid").jqGrid({
    url: '../load_file_here.php',
    editurl: '../edit_file_here.php',
    datatype: "json",
    ...,
    ...,
    colModel: [
    {
        label: 'Foto',
        name: 'foto',
        align: 'left',
        editable: true,
        edittype: 'file',
        editoptions: {
           enctype: "multipart/form-data"
        },
        width: 80,
        search: false
   },

之后,我完成了配置而不是'afterSumit'事件,我放了'afterShowform'并在那里调用一个函数,看看:

$('#jqGrid').navGrid('#jqGridPager',
{
     edit: true,
     add: true,
     del: true,
     search: false,
     refresh: false,
     view: false,
     position: "left",
     cloneToTop: false
 },
 {
     editCaption: "Editar",
     width: "700",
     height: "auto",
     top: "120",
     left: "450",
     recreateForm: true,
     closeAfterEdit: true,
     afterShowForm: takeFile,
     errorTextFormat: function (data) {
          return 'Error: ' + data.responseText
     }
 },{ put add here and dele }

因此, afterShowForm 中的函数名为 takeFile

$(document).ready(function () {
    function takeFile() 
    {
        $("#foto").on("change", function(e) {
           e.preventDefault();

           $.ajaxFileUpload({
               url: "../controller/uploadFile.php",
               secureuri: false,
               fileElementId:'foto',
               dataType: 'json',
               success: function (data, status) {
                  if (data.error == '0')
                  {
                       console.log(data.ok);
                  }else{
                       console.error(data.error);
                  }
              }
          });
       });
   }
}

最后,简单的 uploadFile.php 是:

<?php
    $target_dir = "../../files/";
    $target_file = $target_dir . basename($_FILES["foto"]["name"]);
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image

    $error = "";
    $ok = "";
    if(isset($_FILES))
    {
        if (isset($_FILES['foto']))
        {
            if (move_uploaded_file($_FILES["foto"]["tmp_name"], $target_file)) {
            $ok = "The file has been uploaded.";
            $error = 0;
        } else {
            $error = "Failed to upload file ";
        }
    }

    echo json_encode(array(
        'ok'        => $ok,
        'file_name' => basename( $_FILES["foto"]["name"] ),
        'error'     => $error,
    ));
?>

就是这样,我希望我在某些方面得到了帮助。感谢