jquery-ajax'不要开火

jquery ajax doesn't fire

本文关键字:开火 jquery-ajax      更新时间:2023-09-26

我正试图使用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更改为字符串并返回值)

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,而是您的aspx页面将被处理并输出HTML。查看页面源代码并查看所呈现的实际HTML。您会注意到您的下拉列表是一个select元素,其中有一个类似ctl00$ContentPlaceHolder1$Page$#DDLid

您的jQuery找不到$("#DDL"),因为它不存在。

选项1:

如果您的javascript直接在.aspx页面上,而不是外部的,您可以使用以下命令将生成的客户端id打印到您的页面

 ...$("#<%=DDL.ClientID%>").change(function () {                             
                $.ajax({...

选项2:

您的另一个选项是DropDownList的ClientIDMode设置为static,这样当页面呈现时它不会更改

<asp:DropDownList ID="DDL" runat="server" ClientIDMode="static">
                  <asp:ListItem>aaa</asp:ListItem>
                    <asp:ListItem>bbb</asp:ListItem>
                </asp:DropDownList>

你的url会有问题吗?signToCity.aspx/getStreets看起来不对。也许应该是signToCity/getStreets.aspx

甚至只是signToCity/getStreets