2013-05-15 40 views
0

的形式为:AJAX不张贴到的WebMethod

<form action="upload-document.aspx" onsubmit="sendAndClose();" method="post" enctype="multipart/form-data"> 
    <input name="fileToUpload" id="fileToUpload" type="file" /> 
    <input type="submit" name="submit" value="Send" /> 
</form> 

的AJAX:

function sendAndClose() { 
     currentUrl = location.protocol + '//' + location.host + location.pathname; 

     var data = new FormData(); 
     var file = $("#fileToUpload")[0].files[0]; 

     data.append("name", file.name); 
     data.append("size", file.size); 
     data.append("type", file.type); 
     data.append("file", file); 

     $.ajax({ 
      type: "POST", 
      url: currentUrl + '/Persist', 
      dataType: 'json', 
      data: data, 
      cache: false, 
      contentType: false, 
      processData: false, 
      success: function() { 
       parent.$.fancybox.close(); 
      }, 
      error: function (request, error) { 
       alert("[" + error + "] - FAIL: " + request.responseText); 
       parent.$.fancybox.close(); 
      } 
     }); 
    } 

隐藏代码:

[WebMethod] 
public static bool Persist(object data) 
{ 
    return true; 
} 

时提交表单,它运行AJAX并在进入webmethod之前直接进入错误回调。有人可以告诉我为什么吗?

另外,在'var file'之后,我有一个警告显示文件的名称,大小等等...所以它获取文件,问题是ajax拒绝与代码隐藏通讯。

+0

如果您在请求中运行Fiddler,您会得到什么答复......? http://fiddler2.com/ –

+1

将方法注释为'[HttpPost]'。 –

+0

Calil:不使用mvc:theres没有HttpPostAttribute –

回答

0

我有被在AJAX功能加入这个参数解决了类似的问题:

traditional: true 

因此,尝试此代码为您的AJAX调用:

$.ajax({ 
     type: "POST", 
     url: currentUrl + '/Persist', 
     dataType: 'json', 
     data: data, 
     cache: false, 
     contentType: false, 
     processData: false, 
     traditional: true, 
     success: function() { 
      parent.$.fancybox.close(); 
     }, 
     error: function (request, error) { 
      alert("[" + error + "] - FAIL: " + request.responseText); 
      parent.$.fancybox.close(); 
     } 
    }); 
+0

即时通讯不好意思,但我不知道它是否工作,我已经改变了我的整个代码。 tyvm虽然! –

0

你可以不会调用一个WebMethod http://localhost:40899/upload-document.aspx/Persist。 currentUrl不正确。

+0

我已经使用相同的逻辑从ajax发布到webmethods,他们都从今天开始工作。唯一不同的是,这次它是一个文件即时通讯设法发送。 –

+0

我已经解决了这个问题,我会在这里发布它,但stackoverflow.com不会让我!谢谢。 –

+0

@ user2366528您能否至少解释解决方案的高级解决方案?这将有所帮助。 – Charls

0

从我在评论部分的问题继我想补充一点,你public static bool Persist...方法MUST在页面(ASPX),而不是用户控件(ASCX)。

这是因为页面(ASPX)通过URL对外界“可见”,而用户控件(ASCX)仅在服务器上用于构建页面而不是URI本身,因此外部呼叫者无法访问。

如果您需要调用用户控件中的方法,您需要将Persist方法(使用WebMethod属性)移动到您的页面(ASPX),然后使用该方法调用您的用户控件(ASCX )。