thinkphp 3.2 异步上传图片,出现在<pre>标签,不执行success

本文介绍了在ThinkPHP 3.2中遇到的异步图片上传问题,当上传图片出现在`<pre>`标签中时,导致上传成功后的回调函数不执行。文章提供了一个UploadController的示例,展示了如何处理图片上传,包括设置上传配置、处理上传错误,并通过AjaxFileUpload.js进行文件上传。同时,给出了HTML表单和JavaScript部分的代码,用于选择图片并预览,以及异步提交表单。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<pre name="code" class="php"><?php
use Think\Controller;

class UploadController extends Controller
{

    public function upload()
    {
        $upload = new \Think\Upload(); // 实例化上传类
        $upload->maxSize = 3145728;
        $upload->rootPath = './Public/upload/images/';
        $upload->savePath = '';
        $upload->saveName = array(
            'uniqid',
            ''
        );
        $upload->exts = array( 
            'jpg',
            'gif',
            'png',
            'jpeg'
        );
        $upload->autoSub = false;
        $upload->subName = array(
            'date',
            'Ymd'
        );
        
        // 上传文件
        $info = $upload->upload();
    /*
     *      if(!$info) {// 上传错误提示错误信息
          $this->ajaxReturn($upload->getError());
        }else{// 上传成功 获取上传文件信息
          
            $img = $info['savename'];
            if ($img != "") {
            
                $arr = array(
                    'success'=>true,
                    'img'=>$info['savename'],
                );
//                 $this->ajaxReturn (json_encode($arr),'JSON');
            $this->ajaxReturn($info,'json');
//            $this->ajaxReturn($info['savename']);
            }
        
        }
    }
        
        */
        
     if(!$info) {
	            //捕获上传异常
	            $this->ajaxReturn($upload->getErrorMsg(),'失败',0);
	            exit;
	        }else {
	            
// 	            $this->ajaxReturn($info,'json');
// 	            $this->ajaxReturn($info,'成功',1);
// 	            echo $info;
	                $this->ajaxReturn($info,'json');
// 	                           $this->ajaxReturn($info['savename']);
	            
	        }
	        
        
    }
}

add.html
<script type="text/javascript" src="__PUBLIC__/script/ajaxfileupload.js"></script>
<div class="pageContent">
	<form method="post" action="__URL__/insert/navTabId/__MODULE__" class="pageForm required-validate" onsubmit="return validateCallback(this, dialogAjaxDone)">
		<div class="pageFormContent" layoutH="58">
		
            <div class="unit">
				<label>选择一级栏目:</label>
				<select name="areaId" >
					<volist name="areaList" id="t">
						<option value="{$t.id}">{$t.areaName}</option>
					</volist>
				</select>
			</div>		
			<div class="unit">
				<label>栏目名字:</label>
				<input type="text" id="typename" name=typename class="required" size="50" />
			</div>
			<div>
			<div class="unit" >
				<label>Logo图片(120X120px):</label>
				<input type="file"  size="30" id="uploadUrl" name="uploadUrl" onchange="uploadImg('1')"/>
				<input type="hidden" id="img" name="img"/>
			</div>
			<div id="div" style="display: none;">
				<label>图片预览:</label>
				<img src="" id="review_img1"/>
			</div>
			</div>
		</div>
		<div class="formBar">
			<ul>
				<li><div class="buttonActive"><div class="buttonContent"><button type="submit">提交</button></div></div></li>
				<li><div class="button"><div class="buttonContent"><button type="button" class="close">取消</button></div></div></li>
			</ul>
		</div>
	</form>
</div>
<script type="text/javascript">
function uploadImg(num){
	$.ajaxFileUpload({
		   type: "POST",
		   url: "__APP__/Upload/upload",
		   secureuri:false,
		   fileElementId:"uploadUrl",
		   dataType: "json",
		   cache:false,
		   success: function(msg){
			   alert(msg.uploadUrl.savename);
			   alert("1_33_"+msg.status);
				  alert("222__"+msg.status);
					$("#review_img"+num).attr("src","__PUBLIC__/upload/images/"+msg.uploadUrl.savename);
					var urlsrc = $("#review_img"+num).attr("src");
					var u = urlsrc.substring(urlsrc.lastIndexOf("/")+1);
					$("#img").val(u);
					$("#div").show();
		   },error:function(data, status, e){
			   alert(status+"_____");
			   for(var s in data){
				   alert(data[s]);
			   }
		   }
		});
}
</script>



ajaxFileUpload
jQuery.extend({

    createUploadIframe: function(id, uri)
    {
            //create frame
            var frameId = 'jUploadFrame' + id;

            if(window.ActiveXObject) {
                //add by bdqn_hl 2014-3-2 start
                if(jQuery.browser.version=="9.0"){
                    io = document.createElement('iframe');
                    io.id = frameId;
                    io.name = frameId;
                }else if(jQuery.browser.version=="6.0" ||jQuery.browser.version=="7.0" ||jQuery.browser.version=="8.0"){
                    var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
                    if(typeof uri== 'boolean'){
                        io.src = 'javascript:false';
                    }
                    else if(typeof uri== 'string'){
                        io.src = uri;
                    }
                }
                //add by bdqn_hl 2014-3-2 end
                /*
                var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
                if(typeof uri== 'boolean'){
                    io.src = 'javascript:false';
                }
                else if(typeof uri== 'string'){
                    io.src = uri;
                }
                */
            }
            else {
                var io = document.createElement('iframe');
                io.id = frameId;
                io.name = frameId;
            }
            io.style.position = 'absolute';
            io.style.top = '-1000px';
            io.style.left = '-1000px';

            document.body.appendChild(io);

            return io           
    },
    createUploadForm: function(id, fileElementId)
    {
        //create form   
        var formId = 'jUploadForm' + id;
        var fileId = 'jUploadFile' + id;
        var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');    
        var oldElement = $('#' + fileElementId);
        var newElement = $(oldElement).clone();
        $(oldElement).attr('id', fileId);
        $(oldElement).before(newElement);
        $(oldElement).appendTo(form);
        //set attributes
        $(form).css('position', 'absolute');
        $(form).css('top', '-1200px');
        $(form).css('left', '-1200px');
        $(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 = s.fileElementId;        
        var form = jQuery.createUploadForm(id, s.fileElementId);
        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 
                                        {
                                            $(io).remove();
                                            $(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 io = $('#' + frameId);
            var form = $('#' + formId);
            $(form).attr('action', s.url);
            $(form).attr('method', 'POST');
            $(form).attr('target', frameId);
            if(form.encoding)
            {
                form.encoding = 'multipart/form-data';              
            }
            else
            {               
                form.enctype = 'multipart/form-data';
            }           
            $(form).submit();

        } catch(e) 
        {           
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        }       
        return {abort: function () {}}; 

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

                // Fire the global callback
                if ( s.global ) {
                    (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
                }
            },
    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" )
//        	data = jQuery.parseJSON(jQuery(data).text());
            //data会被加<pre>导致AJAX不走success方法,改为如下形式
//            eval("data = \" "+data+" \" ");
            data = jQuery.parseJSON(jQuery(data).text());
//        alert(data);	
        // evaluate scripts within html
        
        
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
            //alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    }
})


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值