2013-08-16 84 views
0

我有一個ascx文件,其中我正在調用位於另一個文件(aspx代碼後面的文件)的函數的ajax調用。但其結果返回完整的aspx頁面,我在我的函數返回字符串只是,下面是我的代碼 這是我的ascx文件ajax調用ascx文件

$.ajax({ 
      type: "POST", 
      url: "MyFile.aspx/GetData", //url to point your webmethod   
      success: function (Result) { 
       alert('success'); 
       $("#txtlicense").val(Result); 
      }, 
      error: function() { alert('error'); } 
     }); 

,這是MyFile.aspx.cs

[System.Web.Services.WebMethod()] 
     public static string GetData() 
     { 
//Getting data from DB and returning 

     } 

我也嘗試把這種方法在我ascx.cs文件,但它給錯誤

This type of page is not served 

回答

2

你缺少

contentType: "application/json; charset=utf-8", 
dataType: "json", 

請參見下面的工作例子

//後面的代碼的方法聲明爲static

[WebMethod] 
public static string GetSquare(String value) 
{ 
    return value; 
} 

你點擊它這有許多工作要做

<input type="button" id="button" value="Chnageurl" onclick="ajaxcall()" /> 

腳本這個

按鈕
<script type="text/jscript"> 

function ajaxcall(e) { 

      $.ajax({ 
      type: "POST", 
      url: "Default.aspx/GetSquare", 
      contentType: "application/json; charset=utf-8", 
      data: JSON.stringify({ value: "Vinay" }), 
      dataType: "json", 
      success: function (value) { 
      alert(value.d); 
     }, 
     error: function() { alert("Ajax Error"); } 
    }); 
    }; 

+0

非常感謝,第二次我錯過了這個contentType :) –