javascript if()不起作用

时间:2013-10-18 12:17:22

标签: javascript jquery

我有用于上传图片的PHP和JS脚本。 PHP文件返回var err:type,我正在检查JS if return == err:type,但它不起作用。

$(document).ready
(
    function()
    {
        $('#avatar_image_upload_form').submit
        (
            function()
            {
                $('div#avatar_ajax_upload_demo img').attr('src','../../Files/Border/loading.gif');
            }
        );

        $('iframe[name=avatar_upload_to]').load(
            function()
            {
                var result = $(this).contents().text();
                if(result !='')
                {
                    $('div#avatar_ajax_upload_demo img').attr('src',result);
                    if(result == 'err:size')
                    {
                        $('div#avatar_ajax_upload_demo img').attr('src','../../Files/Border/avatar_big.jpg');
                    }
                    if (result == 'err:type')
                    {
                        $('div#avatar_ajax_upload_demo img').attr('src','../../Files/Border/avatar_invalid.jpg');
                    }
                }
            }
        );
    }
);

if(result == 'err:type')不起作用,但result = "err:type"

2 个答案:

答案 0 :(得分:3)

根据此图片:

enter image description here

字符串的开头有很多白线。您需要修剪result字符串以将其删除:

var result = $(this).contents().text().trim();

您最好修复PHP代码,以免发送这些空白行。

答案 1 :(得分:-1)

[WRONG]
也许您的错误在这里:(如果avatar_upload_to不是变量)

$('iframe[name=avatar_upload_to]').load(

应该是

$('iframe[name="avatar_upload_to"]').load(

=====
[测试]
如果你这样做会附加什么:

$('iframe[name=avatar_upload_to]').load(
        function()
        {
            var result = $(this).contents().text();
            console.log(result);
            //or
            alert(':'+result+':');
            if(result !='')
            {
                $('div#avatar_ajax_upload_demo img').attr('src',result);
                if(result == 'err:size')
                {
                    $('div#avatar_ajax_upload_demo img').attr('src','../../Files/Border/avatar_big.jpg');
                }
                if (result == 'err:type')
                {
                    $('div#avatar_ajax_upload_demo img').attr('src','../../Files/Border/avatar_invalid.jpg');
                }
            }
        }
    );