VB.Net環境 Js調用後臺方法獲取數據

最近接觸一個VB.Net的項目,在JS 通過後臺方法獲取數據庫數據時 爲了方便快捷,就直接將後臺方法寫在了對應頁碼的.VB文件裏,此時使用 $.post 時,只能進到 後臺的Page_Load中,不會進入到目標方法裏。此文簡小結了一下 JS 調用 WS, 一般處理程序 和 直接調用 後臺方法的用法,現將可行的方法記錄如下

  • 調用WS。

        創建一個後綴名是.asmx的文件,把方法寫到裏面, ws默認返回值XML,下面的demo 返回值是json。

       

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()>
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")>
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
<ToolboxItem(False)>
Public Class WebServiceTest
    Inherits System.Web.Services.WebService

    <WebMethod()>
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
    Public Function SayHelloWord(Name As String) As String

        Dim MArray()() As String = New String(3)() {}
        MArray(1) = New String() {"sss"}
        MArray(2) = New String() {":"}
        MArray(3) = New String() {"Hello,world"}

        Dim js As JavaScriptSerializer = New JavaScriptSerializer()
        Dim sJSON As String = js.Serialize(MArray)


        Return "{name:""Hello world""}"
    End Function
End Class

前臺JS 調用, 直接把方法名寫在URL 後面即可。

 $.ajax({
       type: "POST",
       url: 'WebServiceTest.asmx/SayHelloWord', 
       data: '{Name:"' + "SayHelloWord" + '"}' ,
                        
       contentType: "application/json; charset=utf-8", 
       dataType: "json",
       success: function (response) {
                           
                response
        },
        error: function (response) {
               response
        }
        });

或者

$.post("WebServiceTest.asmx/SayHelloWord", 
{
    Name:"SayHelloWord"
},
    function (data) {

        data
                    
}
);
  •  調用一般處理程序。

       創建後綴名是ashx的文件,創建時,會自動添加兩個方法 ProcessRequest 和IsReusable 。 其中ProcessRequest 相當於Page_Load 方法。 調用一般處理程序時,會首先調用這個方法。所以我們的處理代碼就寫在這個方法裏面。

 Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        context.Response.ContentType = "text/plain"

        Dim Action As String

        Action = context.Request.Form("Action")

        Dim methodInfo As MethodInfo
        methodInfo = GetType(GeneralTest).GetMethod(Action)
        If methodInfo IsNot Nothing Then
            methodInfo.Invoke(Me, New Object() {context})
        End If

    End Sub

      

  <System.Web.Services.WebMethod>
    Sub SpecificSayHelloWord(ByVal context As HttpContext)

        Dim Speaker As String

        Speaker = context.Request.Form("Speaker")

        Dim stu1 As Student
        stu1 = New Student()
        stu1.Name = "Lily"
        stu1.Gender = "Femail"

        Dim stu2 As Student
        stu2 = New Student()
        stu2.Name = Speaker
        stu2.Gender = "Mail"

        Dim lists As List(Of Student) = New List(Of Student)()
        lists.Add(stu1)
        lists.Add(stu2)

        context.Response.Write(New JavaScriptSerializer().Serialize(lists))



    End Sub

 前臺JS 調用, 需要把方法名寫在參數裏面,後臺反射處理,此處爲 Action: "SayHelloWord"。

$.ajax({
    type: "POST",
    url: 'GeneralTest.ashx',
    data: { Speaker: "Jamie", Action: "SayHelloWord" },
    //data: '{Action:"' + "SayHelloWord" + '"}', //NG
    //contentType: "application/json; charset=utf-8", // NG
    dataType: "json",
    success: function (response) {

        response
    },
    error: function (response) {
        response
    }
});

或者

  $.post('GeneralTest.ashx', 
  {
     Speaker: "Jamie", Action: "SayHelloWord" 
  },
  function (data) {
      data
  }
  );
  • 將方法寫在 後臺頁面裏

      必須是用$.ajax, 不能使用$.post。 $.post的URL 後面跟方法名,不會進到具體的方法,而是會進到 page_load 裏。

而$.ajax 可以進入到具體的方法裏。

<System.Web.Services.WebMethod>  
 Shared Function SayHelloWord() As String

        Dim result As String
        result = "SayHelloWord"

        Return result 
    End Function

Js調用


$.ajax({

   type: "POST",
   url: 'TestTest.aspx/SayHelloWord',
   //data: {Action:"SayHelloWord"}, // NG
   data: '{Action:"' + "SayHelloWord" + '"}', //OK

   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: function (response) {
            response
    },

   failure: function (response) {
            response
    }
    });

但是如果 將aspx頁面的前端內容清空,利用page_load 方法,就可以使用$.post 方法

 

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="TestTest.aspx.vb" Inherits="PAD.TestTest" %>

<%--<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
    </form>
</body>
</html>--%>

$.post 調用

 

        $.post('TestTest.aspx', // 這種方法,TestTest.aspx的 View 需要是空白的頁面。 否則後面會跟View 的html 
                {
                   Speaker: "Jamie", Action: "SayHelloWord" 
                },
                function (data) {

                }
            );

此時的後臺方法可以參考如下:

   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim Action As String
        Action = Request.Form("Action")

        Dim methodInfo As MethodInfo


        methodInfo = GetType(GeneralTest).GetMethod(Action)

        If methodInfo IsNot Nothing Then
            methodInfo.Invoke(Me, New Object() {sender})
        End If
    End Sub

    <System.Web.Services.WebMethod>
    Shared Function SayHelloWord(sender As Object) As String

        Return "{name: ""Hello World!""}"
    End Function

End Class

 

發佈了39 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章