我想調用一個codebehind方法,成功:function()的jquery部分得到執行,但控制似乎並沒有進入被調用的codebehind方法。 aspx頁面:從ajax調用WebMethod,控制不進入webmethod
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication6.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
//$("#Button1").click();
$.ajax({
type: "POST",
url: '<%=ResolveUrl("WebForm1.aspx/Method1")%>',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
$("#test").html("success");
}
});
})
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server" EnablePartialRendering="true" EnablePageMethods="True" />
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div id="test">initial</div>
</form>
aspx.cs代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication6
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static void Method1()
{
WebForm1 w = new WebForm1();
w.Label1.Text = "code behind";
}
}
}
輸出:
Label
success
輸出使我得出這樣的結論成功:函數()的jQuery得到執行(如$(「#test」)。html(「success」);得到執行似乎),但Label1文本仍然是Label,代碼後面的方法似乎沒有被執行。 爲什麼會發生?感謝您的幫助。
你能告訴我應該是數據:和內容類型:在Ajax代碼?因爲我無法成功運行代碼 –
爲什麼你使用post和not get;我沒有看到任何參數?數據是包含查詢參數的java腳本對象,內容類型取決於服務器配置。最常見的contentType:「application/json; charset = utf-8」。您應該檢查瀏覽器中的請求和響應標頭。 –