为什么ajax请求不起作用?
我在 ASP.NET 和使用 JQuery 的 ajax 请求方面度过了一段非常痛苦的时光。我不明白为什么以下不起作用。我错过了什么吗?它似乎可以正常触发请求(没有错误),但它永远不会进入方法内部。
// asp.net webforms (NOT MVC)
public partial class PollManager : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod]
public static string DeletePoll(string pollId)
{
string test = "testing";
return test;
}
}
**Updated Code**
$.ajax({
url: "PollManager.aspx/DeletePoll",
data: { "pollId": "17" },
dataType: "text",
success: function (data)
{
alert(data);
}
});
在母版页中有一个
,我不确定这是否有任何区别。
I have been having a hell of a time with asp.net and ajax request using JQuery. I cannot figure out why the following does not work. Am I missing something? It seems to fire off the request ok (no errors), but it never goes inside the method.
// asp.net webforms (NOT MVC)
public partial class PollManager : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod]
public static string DeletePoll(string pollId)
{
string test = "testing";
return test;
}
}
**Updated Code**
$.ajax({
url: "PollManager.aspx/DeletePoll",
data: { "pollId": "17" },
dataType: "text",
success: function (data)
{
alert(data);
}
});
In the master page there is a <asp:toolkitscriptmanager>
, I'm not sure if that makes any difference.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
嗯...对于一个
数据:“17”
不起作用。您需要执行类似data: {"pollId" : "17"}
的操作Well... for one
data: "17"
isn't going to work. You'd need to do something likedata: {"pollId" : "17"}
您似乎混淆了 ASP.NET Web 服务和 ASP.NET MVC 路由。 ASP.NET Web 表单运行时 (ASPX) 不可能知道如何获取数据 (17) 并将其映射到 pollId 参数。
It seems like you are mixing up ASP.NET web services, and ASP.NET MVC routes. There's no way that the ASP.NET web forms runtime (ASPX) would know how to take your data (17) and map it to the pollId parameter.
您需要将一个
success
处理程序添加到传递到$.ajax
的选项哈希中,如下所示:You need to add a
success
handler to your options hash that are passed into$.ajax
, something like this:我认为您需要删除
[ScriptMethod]
,或者将其更改为[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
因为您不想要 XML 格式的响应。您想要 JSON 响应,不是吗?另外,我不知道它如何序列化字符串对象,但您可能还想尝试返回您定义的对象。就像
new SomeResponseObject(){ MyResponseText="some text" }
那么如果你返回该对象,在 javaScript 中你应该能够像这样访问它
data.MyResponseText
I think you need to remove
[ScriptMethod]
, Or change it to[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
because you don't want XML formatted response. You want JSON response, don't you?Also I don't know how it serializes a string object, but you might want to also try returning an object that you define. Like
new SomeResponseObject(){ MyResponseText="some text" }
Then if you return that object, in javaScript you should be able to access it like this
data.MyResponseText