======================================================
注:本文源代码点此下载
======================================================
我在这里将jquery ajax 调用aspx.net webservice 的几个常用的方法做了一个整理,提供给正在找这方面内容的博友,希望能给学习jquery的朋友一点帮助,可以直接复制代码运行。
ws.aspx 代码
jquery 的webservices 调用
helloworld
传入参数
返回集合
返回复合类型
返回dataset(xml)
服务器处理中,请稍后。
webservice1.asmx.cs
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.services;
using system.data;
namespace jquery.learning
{
///
/// webservice1 的摘要说明
///
[webservice(namespace = "http://tempuri.org/")]
[webservicebinding(conformsto = wsiprofiles.basicprofile1_1)]
[system.componentmodel.toolboxitem(false)]
// 若要允许使用 asp.net ajax 从脚本中调用此 web 服务,请取消对下行的注释。
[system.web.script.services.scriptservice]
public class webservice1 : system.web.services.webservice
{
///
/// 无参数
///
///
[webmethod]
public string helloworld()
{
return "hello world ";
}
///
/// 带参数
///
///
///
///
///
///
[webmethod]
public string getwish(string value1, string value2, string value3, int value4)
{
return string.format("祝您在{3}年里 {0}、{1}、{2}", value1, value2, value3, value4);
}
///
/// 返回集合
///
///
///
[webmethod]
public list getarray(int i)
{
list list = new list();
while (i >= 0)
{
list.add(i--);
}
return list;
}
///
/// 返回一个复合类型
///
///
[webmethod]
public class1 getclass()
{
return new class1 { id = "1", value = "牛年大吉" };
}
///
/// 返回xml
///
///
[webmethod]
public dataset getdataset()
{
dataset ds = new dataset();
datatable dt = new datatable();
dt.columns.add("id", type.gettype("system.string"));
dt.columns.add("value", type.gettype("system.string"));
datarow dr = dt.newrow();
dr["id"] = "1";
dr["value"] = "新年快乐";
dt.rows.add(dr);
dr = dt.newrow();
dr["id"] = "2";
dr["value"] = "万事如意";
dt.rows.add(dr);
ds.tables.add(dt);
return ds;
}
}
//自定义的类,只有两个属性
public class class1
{
public string id { get; set; }
public string value { get; set; }
}
}
本文来自csdn博客,转载请标明出处:http://blog.youkuaiyun.com/shuilv2000/archive/2009/11/24/4863977.aspx
jquery 中的ajax调用webservices 的总结 收藏
使用jquery中javascript:;" οnclick="javascript:tagshow(event, 'ajax');" target="_self">ajax方法访问web服务。
1.ajax方法需要填写:
jscript. code
$.ajax({type:"post",//注明 返回jsoncontenttype:"application/json;utf-8",//collegedepartwebservices.asmx web服务名 /getcollegedepart 方法名http://www.cnblogs.com/tangself/admin/%22collegedepartwebservices.asmx/getcollegedepart%22,//strdepartid 参数名称 collegeid 参数值data:"{strdepartid:"+collegeid+"}",datatype:"json",success:function(result){varjson=nulltry{if(result){//因为返回的是arraylist 所以循环取出其中的值$.each(result,function(i, n){//ddldepart 为下来菜单。循环的向下拉菜单中添加新的选项ddldepart.options[ddldepart.length]=newoption(n.collegedeparttitle,n.collegedepartid);});}}catch(e){alert("错误>>"+e.message);return;}},error:function(data){alert(data.status+">>>"+data.statustext);}});
----
collegedepartwebservices.asmx.cs web服务类
c# code
[webservice(namespace="http://tempuri.org/%22)][webservicebinding(conformsto=wsiprofiles.basicprofile1_1)][scriptservice]publicclasscollegedepartwebservices : system.web.services.webservice{publiccollegedepartwebservices(){//如果使用设计的组件,请取消注释以下行//initializecomponent();}[webmethod][system.xml.serialization.xmlinclude(typeof(collegedepartinfo))]publicarraylistgetcollegedepart(stringstrdepartid){collegedepartbl.flushcollegedepartcache();if(string.isnullorempty(strdepartid))returnnull;arraylist mylist=collegedepartbl.getcollegedepartlistbycollegeid(int.parse(strdepartid));returnmylist;}}
说明:
arraylist 中 存为对象collegedepartinfo
其属性为:stirng collegedeparttitle 和 int collegedepartid
在javascript中
ddldepart.options[ddldepart.length]=new option(n.collegedeparttitle,n.collegedepartid);
option的参数就是依据他们的。
最后重要的是:
类上方添加的
[scriptservice]
必须添加,否则ajax无法调用webservice
本文来自csdn博客,转载请标明出处:http://blog.youkuaiyun.com/shuilv2000/archive/2009/02/20/3914822.aspx
$.ajax(properties)
使用http请求(xmlhttprequest)载入一个远程页面。 这是jquery的低级ajax实现。要查看高级抽象,见$.set、$.post等。 $.ajax()返回创建好的xmlhttprequest对象。多数情况下并不需要直接操纵这个对象,但是如果需要手动中止请求,它也是可用的。 注意:要确保服务器返回正确的mime类型(例如:xml是“text/xml”)。如果返回了错误的mime类型就会导致jquery无法处理的严重问题。
支持的数据类型包括(见datatype选项):
"xml": 返回一个可以由jquery对象处理的xml文档。
"html": 返回纯文本格式的html,包括求值后的脚本标记。
"script": 将响应作为javascript语句求值,并返回纯文本。
"json": 将响应作为json求值,并返回一个javascript对象。
$.ajax()带有一个参数--“名/值对”形式的一个对象,用于初始化和处理请求。
以下就是可用的所有“名/值对”:
(string) url - 要将请求发送到的url地址。
(string) type - 请求的类型 ("post" 或 "get"), 默认是 "get"。
(string) datatype - 期望从服务器端返回的数据类型。无默认值:如果服务器返回xml,就将responsexml传递到回调函数,否则将resposetext传递到回调函数。
(boolean) ifmodified - 只有响应自上次请求后被修改过才承认是成功的请求。是通过检查头部的last-modified值实现的。默认值为false,即忽略
对部分的检查 (number) timeout - 覆盖全局延迟的局部延迟,例如,在其他所有延迟经过1秒钟后,启动一个较长延迟的单独请求。有关全局延迟,见$.ajaxtimeout()。
(boolean) global - 是否为当前的请求触发全局ajax事件处理函数,默认值为true。设置为false可以防止触发像ajaxstart或ajaxstop这样的全局事件处理函数。
(function) error - 当请求失败时调用的函数。这个函数会得到三个参数:xmlhttprequest对象、一个描述所发生的错误类型的字符串和一个可选异常对象(如果有)。
(function) success - 当请求成功时调用的函数。这个函数会得到一个参数:从服务器返回的数据(根据“datatype”进行了格式化)。 (function) complete - 当请求完成时调用的函数。这个函数会得到两个参数:xmlhttprequest对象和一个描述请求成功的类型的字符串。
(object|string) data - 要发送到服务器的数据。如果还不是一个字符串,就自动轮换为一个查询字符串。即附加到get请求的url后面的字符串。要防止自动处理见processdata选项。
(string) contenttype - 设置发送请求的content=type。默认值是 "application/x-www-form-urlencoded", 这个值能满足多数情况。
(boolean) processdata - 在默认的情况下,如果data选项传进的数据是一个对象而不是字符串,将会自动地被处理和转换成一个查询字符串,以适应默认的content-type--"application/x-www-form-urlencoded"。如果想发送domdocuments,就要把这个选项设置为false。
(boolean) async - 在默认的情况下,所有请求都是以异步的方式发送的(值为true)。如果要使用同步方式,需要将此项设置为false。 (function) beforesend - 用于设置自定义头部等信息的预调用函数,接收一个唯一的参数--xmlhttprequest对象。
load a remote page using an http request. this is jquery's low-level ajax implementation. see $.get, $.post etc. for higher-level abstractions. $.ajax() returns the xmlhttprequest that it creates. in most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually. note: make sure the server sends the right mimetype (eg. xml as "text/xml"). sending the wrong mimetype will get you into serious trouble that jquery can't solve. supported datatypes are (see datatype option): "xml": returns a xml document that can be processed via jquery. "html": returns html as plain text, included script tags are evaluated. "script": evaluates the response as javascript and returns it as plain text. "json": evaluates the response as json and returns a javascript object $.ajax() takes one argument, an object of key/value pairs, that are used to initalize and handle the request. these are all the key/values that can be used: (string) url - the url to request. (string) type - the type of request to make ("post" or "get"), default is "get". (string) datatype - the type of data that you're expecting back from the server. no default: if the server sends xml, the responsexml, otherwise the responsetext is passed to the success callback. (boolean) ifmodified - allow the request to be successful only if the response has changed since the last request. this is done by checking the last-modified header. default value is false, ignoring the header. (number) timeout - local timeout to override global timeout, eg. to give a single request a longer timeout while all others timeout after 1 second. see $.ajaxtimeout() for global timeouts. (boolean) global - whether to trigger global ajax event handlers for this request, default is true. set to false to prevent that global handlers like ajaxstart or ajaxstop are triggered. (function) error - a function to be called if the request fails. the function gets passed tree arguments: the xmlhttprequest object, a string describing the type of error that occurred and an optional exception object, if one occured. (function) success - a function to be called if the request succeeds. the function gets passed one argument: the data returned from the server, formatted according to the 'datatype' parameter. (function) complete - a function to be called when the request finishes. the function gets passed two arguments: the xmlhttprequest object and a string describing the type of success of the request. (object|string) data - data to be sent to the server. converted to a query string, if not already a string. is appended to the url for get-requests. see processdata option to prevent this automatic processing. (string) contenttype - when sending data to the server, use this content-type. default is "application/x-www-form-urlencoded", which is fine for most cases. (boolean) processdata - by default, data passed in to the data option as an object other as string will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". if you want to send domdocuments, set this option to false. (boolean) async - by default, all requests are send asynchronous (set to true). if you need synchronous requests, set this option to false. (function) beforesend - a pre-callback to set custom headers etc., the xmlhttprequest is passed as the only argument.
返回值
xmlhttprequest
参数
properties (map): key/value pairs to initialize the request with.
示例
说明:
载入并执行一个javascript文件。
jquery 代码:
$.ajax({ type: "get", url: "test.js", datatype: "script" })
--------------------------------------------------------------------------------
说明:
将数据保存到服务器,并在保存完成后通报用户。
jquery 代码:
$.ajax({ type: "post", url: "some.php", data: "name=john&location=boston", success: function(msg){ alert( "data saved: " + msg ); } });
--------------------------------------------------------------------------------
说明:
同步载入数据。当请求处于活动期间阻塞浏览器。如果必须同步载入数据,最好是通过其他手段来阻止用户的交互,而不是阻塞整个浏览器。
jquery 代码:
var html = $.ajax({ url: "some.php", async: false }).responsetext;
--------------------------------------------------------------------------------
说明:
将一个xml文档作为数据发送到服务器。通过将processdata选项设置为false,可以避免把自动把数据转换为字符串。
jquery 代码:
var xmldocument = [create xml document]; $.ajax({ url: "page.php", processdata: false, data: xmldocument, success: handleresponse });
本文来自csdn博客,转载请标明出处:http://blog.youkuaiyun.com/shuilv2000/archive/2009/11/24/4860787.aspx
绿色通道:好文要顶关注我收藏该文与我联系
======================================================
在最后,我邀请大家参加新浪APP,就是新浪免费送大家的一个空间,支持PHP+MySql,免费二级域名,免费域名绑定 这个是我邀请的地址,您通过这个链接注册即为我的好友,并获赠云豆500个,价值5元哦!短网址是http://t.cn/SXOiLh我创建的小站每天访客已经达到2000+了,每天挂广告赚50+元哦,呵呵,饭钱不愁了,\(^o^)/