簡體   English   中英

jQuery Ajax不會觸發

[英]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")因為它不存在。

選項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>

您的網址可能是問題嗎? signToCity.aspx/getStreets看起來不正確。 也許應該是signToCity/getStreets.aspx

甚至只是signToCity/getStreets嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM