您的位置:首页 > 理论基础 > 计算机网络

javascript 利用xmlhttp访问asp.net 2.0 的webservice

2009-05-06 22:28 363 查看
看了网上的很多,基本都一样,webservice上输入参数,然后用soap传值,感觉不是太方便,每次写一大堆数据

还是用普通的xmlhttp方式,只需要提交简单的参数值对就可以了像:http://localhost/as.aspx?xxx=bb这样的格式

以下为post方法

注:以下代码中的scUI为事先写好的一个组件包,里面包括了一个异步xmlhttp组件

这个组件提供一个setFormParm(formId)方法输入参数

setParam(param)输入简单参数

sendRequestByPost(func,url)方法request 服务器webservice

createXmlHttp()为创建初始化xmlhttp对像

例子webservice页面sc_test.asmx ,比较老套还是sayhello

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
using System.Text;

/// <summary>
/// SC_WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class SC_WebService : System.Web.Services.WebService {

public SC_WebService () {

//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}

[WebMethod]
public string SayHello()
{
HttpRequest Request = System.Web.HttpContext.Current.Request;
string name= Request.Params["name"];
return "hello "+name;
}

}

在WebService中要使用HttpContext必须要在web.config文件中加入以下代码

<webService>

<protocols>

<add name="HttpGet"/>

<add name="HttpPost"/>

</protocols>

</webService>

客户端页面

<html>

<script type="text/javascript" src="../util/js/commonEngine.js"></script>

<!--以上是一个组件包-->

<script type="text/javascript">

//使用scUI中的xmlhttp

function test(){

var fui=new scUI();

fui.createXmlHttp();

fui.setParam("name="+document.getElementById("name").value);

//以pos方式

fui.sendRequestByPost(function(){

if(fui.xmlhttp.readyState==4&&fui.xmlhttp.status==200){

//webservice返回的是xml数据

var reqxml=fui.xmlhttp.responseXml;

//得到里面的值

var text=(reqxml.childNodes)[1].text);

alert(text);

fui=null;

}

},"sc_test.asmx/SayHello");

}

//以上alert(text)值就可以得到SayHello的数据了

//以下是scUI中xmlhttp的部分代码

function scUI(){this.xmlhttp=false;this.paramString="";}

//建立xmlhttp,比较老套,网上有很多,这里省略

//pos方式发送请求

scUI.prototype.sendRequestByPost=function(c,url){

this.xmlhttp.open("post",url,true);

this.xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");

this.xmlhttp.onreadystatechange=c;

this.xmlhttp.send(this.paramString);

}

//设置参数

scUI.prototype.setParam=function(s){

this.xmlhttp.paramString=s; //如果后台出现乱码(比如java后台),则使用encodeURI(encodeURI(s))进行两次编码,然后后台再解码,asp.net一般来说不会出现太大问题,则不必使用
}

</script>

本人目前还在学习asp.net中,原来主要使用java,以上如有不对的地方还请指出
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: