2016-08-20 92 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」。您應該檢查瀏覽器中的請求和響應標頭。 –