开发者

onclick validate file type, if the file is good send some data to the server

I have a form with too many fields. What I am trying to do, is first do some validation using jquery; which is working fine so far. I have an event handler "onclik" which validate the file type that uploaded by the users, and if the file is not image shows a message to the开发者_运维问答 user. If the file is good it should send some data to the server and wait for the response. So far everything is working fine for me, but the ajax doesn't work. Please give me hand Here is my code:

$(document).ready(function(){
  //$(\'#saveData\').bind(\'click\', function() {
    //$(\'#saveData\').live(\'click\', function() {
  $(\'#saveData\').click( function(){
   var ext = $("#articlePhoto").val().split(".").pop().toLowerCase();
   var allow = new Array("gif","png","jpg","jpeg","");
   if(jQuery.inArray(ext, allow) == -1) {
    $("div.fileType").html("some error message");
    $("div.fileType").attr("tabindex",-1).focus();
    return false;
   }
   else
   {
     $.ajax({
       type: "POST",
       url: url+"somefile.php",
       data: "item1=somedata&item2=others",
       success: function(data){
         alert(data); // doesn't work
       }
     });
   }
  });
 });

Thanks


You can't reliably check the type of a file from its filename. Mac and Linux machines have other mechanisms of determining file type than extension, and even under Windows you don't have access to the file-extension-to-type mapping.

Whilst it may be appropriate to print a warning if you do not recognise the file type from its extension (eg. appearing on change on the file upload field), you should not block uploads when this happens.

Other than that, the ajax() call should work, however:

  • you have some stray backslashes (I assume a copy-and-paste typo);
  • you're not returning false when starting the ajax() request. If #saveData is a form submit button, that means the form will still submit on click, and that navigation would cancel the ajax() call;
  • I don't really know what this is supposed to do:

    $("div.fileType").attr("tabindex",-1).focus();
    

    Negative tabindexes are a non-standard IE extension; why do you want to remove the field from the tabbing sequence?

If that's not it, add a error: function() { ... } to the arguments to check the call is actually returning something functional, and check the JS console for errors in general.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜