2013-06-27 37 views
0

我想發送數據使用Ajax從jQuery到C#(注:我發送請求到同一頁面)。 我正在關注本教程http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/獲取錯誤,當做一個jQuery AJAX函數的ASPX頁

注意:這是SharePoint 2010 webpart解決方案上的asp.net 3.5。

這是我的jQuery代碼:

$.ajax({ 
    type: "POST", 
    url: getURLWithoutQuery() + "/saveOrder", 
    data: "{}", 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function (msg) { 
     alert(msg.d); 
    } 
}); 

// return the url of the current page without any query parameters 
function getURLWithoutQuery() { 
    return location.protocol + '//' + location.host + location.pathname; 
} 

,並在C#中,主文件爲PDFLibraryUserControl.ascx.cs。這是具有Page_Load功能的那個。

不過我還有一個類文件名爲SaveStructure.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Web.UI; 
using System.Web.Services; 

namespace PDFLibrary.PDFLibrary 
{ 
    public partial class SaveStructure : Page 
    { 
     [WebMethod] 
     public static int saveOrder() 
     { 
      return 1234; 
     } 
    } 
} 

我希望得到一個警告說1234,而是我得到這個:

enter image description here

是否有事可做與功能saveOrder在另一個文件比主要的?或者,也許我的網址不正確?我不想在其中對網址進行硬編碼,因爲當前頁面是aspx頁面,並且還包含發送POST(到同一頁面)的jQuery代碼。

有誰知道什麼是錯的,可以解決這個問題嗎?

回答

0

將頁面方法放在用戶控件中是一個壞主意,因爲最大的問題是用戶控件不能通過腳本直接訪問(如:jQuery),如.aspx頁面。如果您僅限於將此邏輯放在用戶控件中,那麼我的建議是創建一個Web服務(.asmx),該服務將執行頁面方法要執行的邏輯。可以通過jQuery .ajax()方法直接訪問Web服務,如下所示:

Code from myService.asmx: 
[WebMethod] 
public static int saveOrder() 
{ 
    return 1234; 
} 

Code in SharePoint .aspx page: 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $.ajax({ 
      type: "POST", 
      url: "myService.asmx/saveOrder", 
      contentType: "application/json; charset=utf-8", 
      data: "{}", 
      dataType: "json", 
      success: handleSuccess, 
      error: handleError 
     }); 
    }); 

    function handleSuccess(data, status) { 
     // Do something with successful data retrieval 
    } 

    function handleError(xmlRequest) { 
     // Do something with error 
    } 
</script>