![](/img/trans.png)
[英]jQuery .on click event doesn't always fire on Ajax loaded content
[英]jquery ajax doesn't fire
我正在尝试使用Jquery ajax调用服务器端函数,它不起作用,没有错误。 可能是什么问题? 有一套规则来确保我的$ ajax可以工作吗?
// HTML
<asp:DropDownList ID="DDL" runat="server">
<asp:ListItem>aaa</asp:ListItem>
<asp:ListItem>bbb</asp:ListItem>
</asp:DropDownList>
// JS
$(document).ready(function () {
$("#DDL").change(function () {
$.ajax({
type: "POST",
url: "signToCity.aspx/getStreets",
contentType: "application/json; charset=utf-8"
});
});
});
//服务器端
[WebMethod]
public static void getStreets()
{
string test="no return:just checking by breakpoint if function is working."
}
这是进行AJAX调用的规则的详细信息: 请参阅此处详细信息
$.ajax({
url: 'http://api.joind.in/v2.1/talks/10889',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
var $title = $('<h1>').text(data.talks[0].talk_title);
var $description = $('<p>').text(data.talks[0].talk_description);
$('#info')
.append($title)
.append($description);
},
type: 'GET'
});
将您的服务器端代码更改为以下内容:(将void更改为string并返回值)
C#
[WebMethod]
public static string getStreets()
{
return "no return:just checking by breakpoint if function is working.";
}
jQuery :(为Ajax响应添加处理程序)
$.ajax({
type: "POST",
url: "signToCity.aspx/getStreets",
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response.d);
},
error: function (response) {
console.log('error ' + JSON.stringify(response));
}
});
您是否正在将Web控件的clientidmode
设置为static
? 如果没有,ASP.NET将使用完全不同的ID呈现它
您将以下标记为HTML:
<asp:DropDownList ID="DDL" runat="server">
<asp:ListItem>aaa</asp:ListItem>
<asp:ListItem>bbb</asp:ListItem>
</asp:DropDownList>
但是它不是HTML,而是将处理并输出html的aspx页面。 查看页面源代码,并查看呈现的实际HTML
。 您会注意到您的下拉列表是一个select
元素,其id
类似于ctl00$ContentPlaceHolder1$Page$#DDL
您的jQuery
无法找到$("#DDL")
因为它不存在。
如果您的JavaScript直接位于.aspx
页面上而不位于外部,则可以使用以下命令将生成的客户端ID打印到页面上
...$("#<%=DDL.ClientID%>").change(function () {
$.ajax({...
您的另一个选择是将DropDownList
的ClientIDMode设置为static
,因此呈现页面时它不会改变
<asp:DropDownList ID="DDL" runat="server" ClientIDMode="static">
<asp:ListItem>aaa</asp:ListItem>
<asp:ListItem>bbb</asp:ListItem>
</asp:DropDownList>
您的网址可能是问题吗? signToCity.aspx/getStreets
看起来不正确。 也许应该是signToCity/getStreets.aspx
?
甚至只是signToCity/getStreets
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.