zoukankan      html  css  js  c++  java
  • C#后台程序与HTML页面中JS方法互调(功能类似于Ajax中的DWR)

    此方法适用于 C#中嵌入WebBrowser(浏览器) 通过浏览器中加载的页面与C#的后台代码进行交互。

    一、C#程序

    1、在C#窗体中添加WebBrowser(浏览器),将页面的URL添加到浏览器中。

    2、窗体代码添加 using System.Runtime.InteropServices;

    //和Html页面交互使用 在类的上一行添加 [ComVisible(true)]
    //和Html页面交互使用 在类的构造其中添加 this.webB.ObjectForScripting = this;
    //和Html页面交互使用 如: using System.Runtime.InteropServices;

    namespace slgdjb
    {
    [ComVisible(true)]

    public partial class Frm_Index : Form {

    public Frm_Index() { InitializeComponent(); this.webB.ObjectForScripting = this; }

    }

    }

    3、添加供Html页面调用的方法 如: 该方法的方法名即为Html页面JS中所要调用的方法名

    public string myAction(object para) { //方法内容在此写 }

    4、C#程序调用Html页面JS方法 首先要获得Html页面的Document,然后再调用Html页面的JS方法 如: HtmlDocument doc = webB.Document; string[] objArray = new string[2]; objArray[0] = "a"; objArray[1] = "b";
    //调用Html页面js方法,JSMonth为JS方法名,objArray为传递的参数。
    //JS中不能接收对象,但可以接收整形、字符串、字符串数组。
    doc.InvokeScript("JSMonth",objArray);
    二、Html页面中JS方法调用C#方法

    1、在Html页面JS中调用C#程序的方法,若C#中的方法有返回值,则JS可以得到。 如: //myAction为C#中方法的方法名,para为该方法的参数。 var str = window.external.myAction(para);
    2、供C#调用的Html页面中JS的方法 该方法的方法名即为C#中所要调用的方法名 obj即为要传递的参数。若传递的参数为数组,则在JS 方法中可直接使用arguments[index(数组参数编号)]表示数组的参数值。arguments为JS默认数组参数,其好处在于JS方法不必写传递的参数。
    function JSMonth(obj){ //若obj为数组,则obj[0]等价于arguments[0];其方法名可改写为JSMonth() }

    --------------------------想不起来是为什么要写这篇文章了2011-11-25——————————————

  • 相关阅读:
    【HDOJ】2774 Shuffle
    【POJ】2170 Lattice Animals
    【POJ】1084 Square Destroyer
    【POJ】3523 The Morning after Halloween
    【POJ】3134 Power Calculus
    【Latex】如何在Latex中插入伪代码 —— clrscode3e
    【HDOJ】4801 Pocket Cube 的几种解法和优化
    【HDOJ】4080 Stammering Aliens
    【HDOJ】1800 Flying to the Mars
    SQL语法
  • 原文地址:https://www.cnblogs.com/Rampage/p/2263278.html
Copyright © 2011-2022 走看看