2013-08-16 86 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 :) –