Jquery Ajax方式访问WebService

来源:互联网 发布:胡鞍钢为什么得宠知乎 编辑:程序博客网 时间:2024/06/05 23:42

上一篇博客介绍了再ASP中调用WebService(地址:),现在我们使用Jquery的Ajax方式来访问WebService。现将方法记录下来,方便今后随时查阅学习。


1.远程WebSevice方法介绍

HelloWorld方法没有参数,返回的是一个字符串“HelloWorld”

Test方法接受一个名字为tt的字符串参数,并且返回一个类似回显字符串:“your input is:输入参数tt”


2.编写页面,保存为jqueryandwebservice.html,页面具体代码如下:

<html><head><meta charset="utf-8" /><script type="text/javascript" src="js/jquery-1.7.1.min.js"></script><script type="text/javascript">$(document).ready(function(){$("#HelloWoldBtn").click(function(){$.ajax({type:  "POST",contentType: "application/json",url: "http://localhost/yui/MyFirstWebService.asmx/HelloWorld",data: "",dataType: "json",success: function(result){var final_result = result.d;alert("final_result:"+final_result);}});});$("#TestBtn").click(function(){$.ajax({type:  "POST",contentType: "application/json",url: "http://localhost/yui/MyFirstWebService.asmx/Test",data: "{tt:'test'}",dataType: "json",success: function(result){var final_result = result.d;alert("final_result:"+final_result);}});});});</script></head><body><div><p>Jquery Ajax调用WebService示例</p><form id="form1"><p><input type="button" id="HelloWoldBtn" value="HelloWorld" /></p><p><input type="button" id="TestBtn" value="Test" /></p></form></div></body></html>


3.点击HelloWorld按钮,结果如图:

4.点击Test按钮,结果如图:




注意:

1)Ajax请求中,需要注意的点是:contentType必须填写application/json,dataType必须是json。

2)Ajax请求返回的数据也是json格式,并且服务器返回的结果保存在d的结果中,所以必须使用result.d来获取结果。


0 0
原创粉丝点击