我正在尝试调用一个代码隐藏方法,jquery部分的success: function()被执行了,但是控件似乎没有进入被调用的代码隐藏方法中。aspx页面:
<%@ 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的success: function()被执行了(就像$(“#.html”) Label1 (“success”);被执行了),但是测试文本仍然是标签,方法后面的代码似乎没有被执行。为什么会发生这种情况?非常感谢您的帮助。
发布于 2016-08-20 16:56:38
问题出在客户端和服务器端。这是你在使用java script Ajax request和ASP时必须理解的。
首先,JavaScript代码在客户机上运行,而ASP.net在服务器端运行。
当使用js执行ajax请求时,它期望来自服务器的一些结果,这些结果通常是json、xml、内存流。您可以获取此信息,并在客户端对其执行某些操作。
当您在服务器端的web方法中执行诸如:w.Label1.Text = "code behind";之类的内容时,请求将不起作用,因为您不会在服务器为asp.net控件生成值的情况下执行完整的页面刷新。
为了让您的代码正常工作,您应该编写如下代码
public class Result
{
public string State{get;set;}
public string Message{get;set;}
}
public static Result Method1()
{
return new Result{State="Success",Message="code behind" };
}JS:
$.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(result.State);
$("#Label1").html(result.Message);
}
});https://stackoverflow.com/questions/39052100
复制相似问题