jQuery跨域调用WebService举例
html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>jquery跨域调用WebService(getJson)</title>
<style type="text/css">
*
{
font: 12px 宋体;
margin: 0px;
padding: 0px;
}
body
{
padding: 5px;
}
#container .search
{
height: 20px;
}
#container .result
{
margin-top: 5px;
}
#txtUserName
{
float: left;
}
#btnSearch
{
float: left;
margin: 0px 0px 0px 5px;
width: 78px;
height: 16px;
text-align: center;
line-height: 16px;
background-color: #eee;
border: solid 1px #BABABA;
cursor: pointer;
}
#btnSearch:hover
{
width: 76px;
height: 14px;
line-height: 14px;
background-color: #fff;
border-width: 2px;
}
.mark
{
color: Blue;
}
</style>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
//用户信息(全局)
var userData = {
//WebServices地址(GetUserList=方法名称,?jsoncallback=?--必须包含)
requestUrl: "http://localhost:54855/PersonalServices.asmx/GetUserList?jsoncallback=?",
//方法参数(用户名可用","分隔开来查询多个用户信息)
requestParams: { userName: null },
//回调函数
requestCallBack: function (json) {
if (json.ResponseStatus == 1) {//成功获取数据
var addRow = function (key, value) {
return "<span>" + key + ":</span><span class=\"mark\">" + value + "</span><br/>";
}
userData.resultData = json.ResponseData;
var resultHtml = "";
$(userData.resultData).each(function () {
resultHtml += addRow("姓名", this.Name);
resultHtml += addRow("年龄", this.Age);
resultHtml += addRow("性别", this.Sex);
resultHtml += addRow("备注", this.Remark);
resultHtml += "<br/>";
});
$(".result").html(resultHtml);
} else $(".result").html(json.ResponseDetails); //无数据或者后台处理失败!
},
//查询得到的数据
resultData: null
};
$(function () {
//绑定文本框的键盘事件
$("#txtUserName").keyup(function () {
if ($.trim($(this).val()) == "") {
$(".result").html("请输入查询用户名!");
} else {
userData.requestParams.userName = $(this).val();
$(".result").html("");
}
});
//绑定查询按钮单机事件
$("#btnSearch").click(function () {
if (userData.requestParams.userName) {
$.getJSON(userData.requestUrl, userData.requestParams, userData.requestCallBack);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="container">
<div class="search">
<input type="text" id="txtUserName" /><div id="btnSearch">
查 询</div>
</div>
<div class="result">
</div>
</div>
</form>
</body>
</html>

WebServices.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
#region 命名空间 using Newtonsoft.Json; #endregion namespace WebService
{
/// <summary>
/// PersonalServices 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class PersonalServices : System.Web.Services.WebService
{
#region 获取用户信息 [WebMethod]
public void GetUserList(string userName)
{
List<Personal> m_PersonalList = new List<Personal>();
string[] strArr = userName.Split(',');
foreach (string item in strArr)
{
Personal m_Personal = GetUserByName(item);
if (m_Personal != null)
{
m_PersonalList.Add(m_Personal);
}
}
ResponseResult responseResult = new ResponseResult();
if (m_PersonalList.Count == )
{
responseResult.ResponseDetails = "没有查到该用户!";
responseResult.ResponseStatus = ;
}
else
{
responseResult.ResponseData = m_PersonalList;
responseResult.ResponseDetails = "查询用户信息成功!";
responseResult.ResponseStatus = ;
}
string jsoncallback = HttpContext.Current.Request["jsoncallback"];
//返回数据的方式
// 其中将泛型集合使用了Json库(第三方序列json数据的dll)转变成json数据字符串
string result = jsoncallback + "(" + JsonConvert.SerializeObject(responseResult, Formatting.Indented) + ")";
HttpContext.Current.Response.Write(result);
HttpContext.Current.Response.End();
} #endregion #region 模拟数据库处理结果 /// <summary>
/// 根据用户名查询用户
/// </summary>
/// <param name="userName">用户名</param>
/// <returns></returns>
Personal GetUserByName(string userName)
{
List<Personal> m_PersonalList = new List<Personal>();
m_PersonalList.Add(new Personal()
{
Id = "",
Name = "liger_zql",
Sex = "男",
Age = ,
Remark = "你猜......"
});
m_PersonalList.Add(new Personal()
{
Id = "",
Name = "漠然",
Sex = "女",
Age = ,
Remark = "猜不透......"
});
foreach (Personal m_Personal in m_PersonalList)
{
if (m_Personal.Name == userName)
{
return m_Personal;
}
}
return null;
} #endregion #region json数据序列化所需类 /// <summary>
/// 处理信息类
/// ResponseData--输出处理数据
/// ResponseDetails--处理详细信息
/// ResponseStatus--处理状态
/// -1=失败,0=没有获取数据,1=处理成功!
/// </summary>
class ResponseResult
{
public List<Personal> ResponseData { get; set; }
public string ResponseDetails { get; set; }
public int ResponseStatus { get; set; }
} /// <summary>
/// 用户信息类
/// </summary>
class Personal
{
public string Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
public string Remark { get; set; }
} #endregion
}
}

WebService项目配置文件

<system.web>
<!--提供Web服务访问方式-->
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
<add name="Documentation"/>
</protocols>
</webServices>
</system.web>

由于使用jquery.getJson的方式调用Web服务后,传递中文时会造成中文乱码问题:

所以在配置文件中应配置如下内容:

<system.web>
<!-- 设定传参乱码问题 -->
<globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8"/>
</system.web>

调用截图如下:

最后附上源码:JqCrossDomain.zip

jQuery跨域调用WebService的更多相关文章

  1. jquery跨域调用wcf

    使用jquery跨域调用wcf服务的时候会报如下错误 $.ajax({ url: 'http://localhost:28207/Service1.svc/GetData', method: 'get ...

  2. 跨域调用webservice

    本人第一次在博客园写博客. 最近研究js的跨域调用,举个小例子. ASP.net 中webservice 源代码 /// <summary>    /// Service1 的摘要说明   ...

  3. jQuery跨域调用Web API

    我曾经发表了一篇关于如何开发Web API的博客,链接地址:http://www.cnblogs.com/guwei4037/p/3603818.html.有朋友说开发是会开发了,但不知道怎么调用啊? ...

  4. Jquery跨域调用

    今天在项目中须要做远程数据载入并渲染页面,直到开发阶段才意识到ajax跨域请求的问题,隐约记得Jquery有提过一个ajax跨域请求的解决方式,于是即刻翻出Jquery的API出来研究,发现JQuer ...

  5. ajax跨域调用webservice例子

    [WebMethod(Description = "这是一个描述")] public void GetTIM() { try { SqlDataAdapter da = new S ...

  6. Jquery跨域调用后台方法

    //前端JS function CallHandlerByJquery() { var url = "http://" + window.location.hostname + & ...

  7. ajax使用jsonp跨域调用webservice error错误信息"readyState":4,"status":200,"statusText":"success"

    主要还是接口写有问题 至于ajax保持简洁写法即可 $.ajax({ dataType: 'jsonp', type: ‘get’, data: {}, url: '' })

  8. jquery Ajax跨域调用WebServices方法

    由于公司需要开发一个手机页面,想提供给同事直接在手机上可以查询SAP资料.数据需要使用js调用webserver来获取. 因为初次使用Jquery调用Webserver,所以期间并不顺利.测试调用We ...

  9. Jquery的跨域调用

    JQuery1.2后getJSON方法支持跨域读取json数据,原理是利用一个叫做jsonp的概念.当然,究其本质还是通过script标签动态加载js,似乎这是实现真正跨域的唯一方法. getJSON ...

随机推荐

  1. Java原子类--AtomicLongArray

    转载请注明出处:http://www.cnblogs.com/skywang12345/p/3514604.html AtomicLongArray介绍和函数列表 在"Java多线程系列-- ...

  2. Promise.then方法的执行顺序例题分析

    1. 当Promise对象作为resolve的参数时 const p = Promise.resolve(); const p1 = Promise.resolve(p); //就是p const p ...

  3. pytz

    pytz django的模型类中使用的 DateTimeField 字段,自动添加下来的携带有时区信息,2019-06-19T03:58:11.937945Z 在我的逻辑中需要对时间进行比较,我使用了 ...

  4. P1449 后缀表达式

    题目描述 所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级). 如:3*(5–2)+7对应 ...

  5. 好久木来了,一直忙于项目(加懒惰),今天讲讲vuecli3.0的使用

    vue更新换代很快,马上vue都要出3.0了,这是一个巨大的变革,不过今天讲的是vuecli3.0,里面使用的vue仍然是2的,所有可以放心大胆使用. Vue CLI 是一个基于 Vue.js 进行快 ...

  6. 位于0/nut文件里的'Calculated'边界条件是什么意思?【翻译】

    翻译自:CFD-online 帖子地址:http://www.cfd-online.com/Forums/openfoam-pre-processing/140984-what-does-calcul ...

  7. @AUTORELEASEPOOL

    Swift 在内存管理上使用的是自动引用计数 (ARC) 的一套方法,在 ARC 中虽然不需要手动地调用像是 retain,release 或者是 autorelease 这样的方法来管理引用计数,但 ...

  8. DES算法实现

    概述(团队项目) DES是一个分组加密算法,它以64位为分组对数据加密.同时DES也是一个对称算法:加密和解密用的是同一个算法.DES是一个包含16个阶段的"替换–置换"的分组加密 ...

  9. 为什么ROC曲线不受样本不均衡问题的影响

    转自:https://blog.csdn.net/songyunli1111/article/details/82285266 在对分类模型的评价标准中,除了常用的错误率,精确率,召回率和F1度量外, ...

  10. WebService(axis2),整合springmvc

    webservice:不同组织或者部门之间互通数据 https://www.cnblogs.com/buggou/p/8183738.html 1 package com.sh.test; 2 3 4 ...