page method question
I'm building an asp.net page that uses a page method call from jquery. This is a simple test page but I can't get it to work and I can't see why.
I added a script manager to the aspx. Here's the javascript function:
<script type="text/javascript">
function CallGetLoaded() {
var ConfirmLoad = "test string";
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetLoaded",
data: ConfirmLoad,
contentType: "application/text; charset=utf-8",
dataType: "text",
success: successLoadLeads,
error: errorLoadLeads
});
};
function successLoadLeads(thereturn) { alert((thereturn)); };
function errorLoadLeads() { alert("problem getting return"); };
</script>
And here's the full code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using System.Web.开发者_高级运维Services;
public partial class Pages_TestPage : System.Web.UI.Page
{
[WebMethod]
public static string GetLoaded(string ConfirmLoad)
{
string ResultString = "got test";
return ResultString;
}
}
Instead of getting back a simple string in the alert popup, I'm sometimes getting back the HTML of the whole page and sometimes the error function; not sure why it varies. What am I missing?
Thanks for your suggestions.
I have made some small changes to your code.
- Changed your
contentType
,data
anddataType
of your$.ajax
request - Changed your
onsuccess
handler to check for.hasOwnProperty("d")
- Changed your
onerror
handler so that you may see what the actual error is.
I strongly believe that you had a parse error since you used text
for parsing and retrieving.
Here is a sample done from your code that works.
The MarkUp
<asp:Button ID="testclick" runat="server" Text="Click Me"/>
The Scripts
$(function () {
$('#testclick').click(function (e) {
CallGetLoaded();
e.preventDefault();
});
});
function CallGetLoaded() {
var ConfirmLoad = "test string";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "TestPage.aspx/Getloaded",
data: "{'ConfirmLoad':'" + ConfirmLoad + "'}",
dataType: "json",
success: function (msg) {
var data = msg.hasOwnProperty("d") ? msg.d : msg;
OnSucessCallBack(data);
},
error: function (xhr, status, error) {
alert(xhr.statusText);
}
});
};
function OnSucessCallBack(data) {
alert(data);
}
The Code-Behind
[WebMethod]
public static string GetLoaded(string ConfirmLoad)
{
string ResultString = "got test";
return ResultString;
}
P.S: As FiveTools have correctly pointed out,
is unnecessary. url:"../Pages/TestPage.aspx/Getloaded"
url:"TestPage.aspx/Getloaded"
will do.
try url: "TestPage.aspx/GetLoaded",
精彩评论