2016-08-20 90 views
1

我想调用一个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,代码后面的方法似乎没有被执行。 为什么会发生?感谢您的帮助。

回答

1

问题是客户端与服务器端。当你在ASP中使用java脚本Ajax请求时,你必须了解它。

首先,JavaScript代码在客户机上运行,​​而ASP.net运行在服务器端。

当使用js执行ajax请求时,它需要来自服务器的一些结果,通常是json,xml,内存流。您可以在客户端获取这些信息并对其进行处理。

当您执行类似于:w.Label1.Text = "code behind";在Web方法的服务器端请求将不起作用,因为您不会在服务器为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); 
    } 
    }); 
+0

你能告诉我应该是数据:和内容类型:在Ajax代码?因为我无法成功运行代码 –

+0

为什么你使用post和not get;我没有看到任何参数?数据是包含查询参数的java脚本对象,内容类型取决于服务器配置。最常见的contentType:“application/json; charset = utf-8”。您应该检查浏览器中的请求和响应标头。 –