JS:将JS插入jQuery / AJAX代码中

时间:2013-05-11 03:27:36

标签: javascript jquery ajax

我想知道如何在jQuery-AJAX代码中使用我的Javascript代码:

JS代码

var error="";

function Checkfiles() {
    var fup = document.getElementById('flUpload');
    var fileName = fup.value;
    var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
    var chkext = ext.toLowerCase();

    if(chkext=="gif" || chkext=="jpg" || chkext=="jpeg" || chkext=="png") { 
        return true;
    } else { return false; }
} // Checkfiles

function Checksize() { 
    var iSize;
    if ($("#flUpload")[0].files[0]){ iSize = ($("#flUpload")[0].files[0].size / 1024);}
    if(Checkfiles()==true && iSize < 51.200) { return true; } else { error += "- Only GIF, PNG, JPG images, smaller than 50 KB."; return false; }
} //Checksize

这个jQuery代码:

$(document).ready(function() {

$("#ff1").submit(function(e){
    // prevent submit
    e.preventDefault();

    var email = document.getElementById("email").value;
    var title = document.getElementById("title").value;
    var url = document.getElementById("url").value; 
    var parametros = {"emaail":email, "tiitle":title, "uurl":url, "filee":file};

    $.ajax({
        data: parametros,
        url: 'validate.php',
        type: 'post',
        context: this,
        error: function (response) {
            alert("An error has occurred! Try Again!");
        },
        success: function (response) {
            if($.trim(response) == 'bien') { 
                this.submit(); // submit, bypassing jquery bound event
            } 
            else {
                $("#ajax_call_val").html('<div id="validation"><ul>'+response+'</ul></div>');
            }
        }
    });

});

});

我想用我的Javascript代码验证文件输入,如果Checksize()返回true,则在AJAX代码中应该是以下行:

$("#ajax_call_val").html('<div id="validation"><ul>'+response+'</ul></div>');

如果Checksize()返回false,则应为:

$("#ajax_call_val").html('<div id="validation"><ul>'+response+'<li>Only GIF, PNG, JPG images, smaller than 50 KB</li></ul></div>');

提前致谢!

1 个答案:

答案 0 :(得分:1)

在成功函数中执行:

if (Checksize()) {
    $("#ajax_call_val").html('<div id="validation"><ul>'+response+'</ul></div>');
} else {
    $("#ajax_call_val").html('<div id="validation"><ul>'+response+'<li>Only GIF, PNG, JPG images, smaller than 50 KB</li></ul></div>');
}

将您的上述内容与代码相结合:

var error="";

function Checkfiles() {
    var fup = document.getElementById('flUpload');
    var fileName = fup.value;
    var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
    var chkext = ext.toLowerCase();

    if(chkext=="gif" || chkext=="jpg" || chkext=="jpeg" || chkext=="png") { 
        return true;
    } else { return false; }
} // Checkfiles

function Checksize() { 
    var iSize;
    if ($("#flUpload")[0].files[0]){ iSize = ($("#flUpload")[0].files[0].size / 1024);}
    if(Checkfiles()==true && iSize < 51.200) { return true; } else { error += "- Only GIF, PNG, JPG images, smaller than 50 KB."; return false; }
} //Checksize

$(document).ready(function() { //blah });