注:需要的js文件与组件(jquery-1.4.2.min.js和Newtonsoft.Json)

同域:要调用的webservice与ajax请求页面在同一个网站下(本文中都是本地测试)。

数据库(表名 CarUsing  cuid 主键自增列 int , carUsing varchar(100) 车辆用途)

一、创建webService。

在框架4.0中找不到Asp.Net Web服务应用程序。将框架更改为4.0以下即可找到。也创建一个网站在网站中添加webService。

建立的web服务应用程序的结构如下。

CarUsing.cs中代码如下:

using System;
using System.Collections.Generic;
using System.Text; public class CarUsing
{
public CarUsing() { } public CarUsing(string careUsing)
{
this.careUsing = careUsing;
} public CarUsing(int cuid, string careUsing)
{
this.cuid = cuid;
this.careUsing = careUsing;
} private int cuid; public int Cuid
{
get { return cuid; }
set { cuid = value; }
} private string careUsing; public string CareUsing
{
get { return careUsing; }
set { careUsing = value; }
}
}

Service1.asmx中的代码如下:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using Newtonsoft.Json;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Serialization; namespace WebService2
{
/// <summary>
/// Service1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempri/url")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod(Description = "添加")]
public string AddCarUsing(string cusing)
{
string result = "";
string sql = string.Format("insert into CarUsing values(@carUsing)");
SqlParameter para = new SqlParameter("@carUsing", cusing);
result = SqlHelper.ExecuteNonQuery(sql, CommandType.Text, para).ToString();
return result;
} [WebMethod(Description = "修改")]
public string UpdateCarUsing(int id,string cusing)
{
string result = "";
string sql = string.Format("update CarUsing set carUsing =@carUsing where cuid=@cuid");
SqlParameter[] paras = {
new SqlParameter("@carUsing",cusing),
new SqlParameter("@cuid", id)
};
result = SqlHelper.ExecuteNonQuery(sql, CommandType.Text, paras).ToString();
return result;
} [WebMethod(Description = "删除")]
public string delCarUsing(string cuid)
{
string result = "";
string sql = string.Format("delete from CarUsing where cuid=@cuid");
SqlParameter para = new SqlParameter("@cuid", Convert.ToInt32(cuid));
result = SqlHelper.ExecuteNonQuery(sql, CommandType.Text, para).ToString();
return result;
} [WebMethod(Description = "根据id查询数据")]
public string getCarUsingBycuid(string cuid)
{
string json = "";
CarUsing caru = new CarUsing();
string sql = "select * from CarUsing where cuid =@cuid";
SqlParameter para = new SqlParameter("@cuid", Convert.ToInt32(cuid));
using (SqlDataReader dr = SqlHelper.ExecuteReader(sql, CommandType.Text, para))
{
while (dr.Read())
{
caru = new CarUsing(
Convert.ToInt32(dr["cuid"]),
dr["carUsing"].ToString()
);
}
json = JsonConvert.SerializeObject(caru);
}
return json;
} [WebMethod(Description = "查询所有数据")]
public string getCarUsing()
{
string json = "";
List<CarUsing> CarUsings = new List<CarUsing>();
string sql = "select * from CarUsing order by cuid desc";
using (SqlDataReader dr = SqlHelper.ExecuteReader(sql, CommandType.Text))
{
while (dr.Read())
{
CarUsing carUsing = new CarUsing(
Convert.ToInt32(dr["cuid"]),
dr["carUsing"].ToString()
);
CarUsings.Add(carUsing);
}
json = JsonConvert.SerializeObject(CarUsings);
}
return json;
}
}
}

注:在web.config中的<system.web>中添加

<webServices>
<protocols>
<add name="HttpPost"/>
<add name="HttpGet"/>
</protocols>
</webServices>

  

二、建立web网站

添加Newtonsoft.Json.dll组件,且添加js文件

在网站根目录下新建一个html页面HTMLPage1.htm。

代码如下:

<html>
<head runat="server">
<title>车用途Ajax+Json</title>
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var WebServiceURL = "http://localhost:22657/";
//js版本必须2.0以下,2.0以上不ie8不支持get等方法。
function showAll() {
//返回Dafault页面的数据。 $.ajax({
type: "POST", //访问WebService使用Post方式请求
contentType: "application/json", //WebService 会返回Json类型
url: WebServiceURL + "Service1.asmx/getCarUsing", //调用WebService的地址和方法名称组合 ---- WsURL/方法名
data: "{}", //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到
dataType: 'json',
success: function (json) {
//回调函数,result,返回值
var jsons = eval('(' + json.d + ')');
var html = "<table border=1 bordercolor=6d6d6d cellspacing = 1>";
html += "<tr backgroundcolor='yellow'><td>Id</td><td>用途</td><td>操作</td></tr>";
for (var i = 0; i < jsons.length; i++) {
html += "<tr>";
html += "<td>" + jsons[i].Cuid + "</td><td>" + jsons[i].CareUsing + "</td><td><a href='javascript:;' onclick='UpdateInit(" + jsons[i].Cuid + ")'>修改</a> <a href='javascript:;' onclick='if(confirm(\"确定删除嘛?\")){Delete(" + jsons[i].Cuid + ");}'>删除</a></td>";
html += "</tr>";
}
html += "</table>"
$("#div1").html(html);
}
});
}
//准备添加
function Insert() {
$("#d1").show();
$("#d2").show(300);
} function InsertInfo() {
var json = '{"cusing":"' + form1.txtcarUsing.value + '"}';
$.ajax({
type: "POST",
contentType: "application/json",
url: WebServiceURL + "Service1.asmx/AddCarUsing",
data: json,
dataType: 'json',
success: function (result) {
showAll();
CloseDiv();
},
error: function (result) {
alert("操作失败");
}
});
} function Delete(id) {
var json = '{"cuid":"'+id+'"}';
$.ajax({
url: WebServiceURL + "Service1.asmx/delCarUsing",
contentType: "application/json;charset=utf-8",
type: "POST",
dataType: "json",
data: json,
success: function (json) {
showAll();
},
error: function (json) {
alert("操作失败!");
}
});
}
//修改初始化
function UpdateInit(cuid) {
var json = '{"cuid":"' + cuid + '"}';
Insert(); //弹出修改框。
$.ajax({
type: "POST",
contentType: "application/json",
url: WebServiceURL + "Service1.asmx/getCarUsingBycuid",
data: json,
dataType: 'json',
success: function (result) {
var json = eval('[' + result.d + ']');
form1.txtcarUsing.value = json[0].CareUsing;
form1.txtid.value = json[0].Cuid;
cuid = json[0].Cuid;
},
error: function (json) {
alert("获取数据失败!");
}
});
}
//发送修改
function UpdateSend(id) {
var json = '{"id":' + form1.txtid.value + ',"cusing":"' + form1.txtcarUsing.value + '"}';
$.ajax({
url: WebServiceURL + "Service1.asmx/UpdateCarUsing",
contentType: "application/json;charset=utf-8",
type: "POST",
dataType: "json",
data:json,
success: function (json) {
showAll();
CloseDiv();
},
error: function (msg) {
alert("操作失败!");
}
});
}
function CloseDiv() {
$('#d1').hide(500);
$('#d2').hide(500);
}
</script>
</head>
<body onload="showAll()">
<form id="form1" runat="server">
<input type="button" value="添加车源用途" onclick="Insert()" />
<div id="div1">
</div>
<div id="d1" style="width: 100%; display: none; height: 100%; position: absolute;
left: 0px; top: 0px; filter: alpha(opacity=70);">
</div>
<div id="d2" style="width: 100%; display: none; height: 100%; position: absolute;
left: 0px; top: 0px;">
<table width="100%" height="100%">
<tr>
<td valign="middle" align="center">
<div style="width: 300px; height: 200px; background-color: White; border: 3px red solid;">
<input type="button" value="隐藏" onclick="CloseDiv()" />
<input type="hidden" id="txtid" />
用途:<input type="text" id="txtcarUsing" />
<input type="button" value="添加" onclick="InsertInfo()" />
<input type="button" value="修改" onclick="UpdateSend()" />
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

  

运行界面如下:

Ajax调用webService(一) 不跨域。的更多相关文章

  1. ajax调用.net API项目跨域问题解决

    ajax调用.net API项目,经常提示跨域问题.添加如下节点代码解决:httpProtocol <system.webServer> <handlers> <remo ...

  2. ASP.NET实现二维码 ASP.Net上传文件 SQL基础语法 C# 动态创建数据库三(MySQL) Net Core 实现谷歌翻译ApI 免费版 C#发布和调试WebService ajax调用WebService实现数据库操作 C# 实体类转json数据过滤掉字段为null的字段

    ASP.NET实现二维码 using System;using System.Collections.Generic;using System.Drawing;using System.Linq;us ...

  3. Ajax调用WebService接口样例

    在做手机端h5的应用时,通过Ajax调用http接口时没啥问题的:但有些老的接口是用WebService实现的,也来不及改成http的方式,这时通过Ajax调用会有些麻烦,在此记录具体实现过程.本文使 ...

  4. 跨域调用webapi web端跨域调用webapi

    web端跨域调用webapi   在做Web开发中,常常会遇到跨域的问题,到目前为止,已经有非常多的跨域解决方案. 通过自己的研究以及在网上看了一些大神的博客,写了一个Demo 首先新建一个webap ...

  5. Ajax调用WebService(一)

    Ajax调用WebService(一) http://www.cnblogs.com/leslies2/archive/2011/01/26/1934889.html 分类: Ajax 使用技术 We ...

  6. Jquery ajax调用webservice总结

    jquery ajax调用webservice(C#)要注意的几个事项: 1.web.config里需要配置2个地方 <httpHandlers>      <remove verb ...

  7. Ajax调用WebService

    前台代码: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1 ...

  8. Jquery Ajax 调用 WebService

    原文:http://www.cnblogs.com/andiki/archive/2010/05/17/1737254.html jquery ajax调用webservice(C#)要注意的几个事项 ...

  9. 使用ajax调用webservice加载table

    写了个ajax调用webservice动态加载表格的案例 不废话直接上代码 webservice代码: /// <summary> /// 首页显示会员信息 /// </summar ...

  10. Ajax请求WCF服务以及跨域的问题解决

    Ajax请求WCF服务以及跨域的问题解决 这两天准备重构一下项目,准备用纯html+js做前台,然后通过ajax+WCF的方式来传递数据,所以就先研究了一下ajax访问的wcf的问题,还想到还折腾了一 ...

随机推荐

  1. Expires、Last-Modified、Etag缓存控制

    当请求一个页面时,如果浏览器使用本地缓存,因此我们经常会看到一个HTTP请求为304状态.或者显示200状态,在chrome下标注是from cache,在火狐下会标注BFCache: 我们希望在服务 ...

  2. apache静态文件配置

    开发环境配置 需要下面几个步骤 1. 在app目录下创建static目录,将静态文件和相关文件夹放到此目录下,如your_app/static/img等 2. 确保settings.py中的INSTA ...

  3. Python中函数参数传递问题

    先上两个例子: http://python.jobbole.com/85231/ a = 1 def fun(a): a = 2 fun(a) print a # 结果为1 fun(a)中的a,可以看 ...

  4. Net Core 项目实战之权限管理系统(0)

    0 前言 Net Core 项目实战之权限管理系统(0) 无中生有   0 http://www.cnblogs.com/fonour/p/5848933.html 学习的最好方法就是动手去做,这里以 ...

  5. asp.net 后台使用js弹窗失效问题

    1.这些事件输出来前后都变成JS代码了,看到到这样的代码的了.会变成<script>alert('合同号XXX已存在')</script>首先后台调试一下看看Page.Clie ...

  6. struts2整合spring出现的Unable to instantiate Action异常

    在struts2整合spring的时候,完全一步步按照官方文档上去做的,最后发现出现 Unable to instantiate Action,网上一搜发现很多人和我一样的问题,配置什么都没有错误,就 ...

  7. BROCADE 300和MD3200扩展柜FC SAN,截图

    这表示俺玩过,其实,这个光交换机在只有一个共享存储的情况下,可用可不用. FC BROCADE只是为了方便后期扩展. FC SAN之类的识别不靠IP,因为不是IP SAN嘛.但也是自己的识别体系.

  8. java数据安全(一)

    在java开发中,常常需要考虑数据安全问题,然不仅仅需要考虑数据存储的安全,还需要考虑数据的传输安全.自从有了数据安全问题后,密码学也就出来了.了解数据安全,首先需要了解密码学 1.什么是密码学 密码 ...

  9. COJ 0501 取数游戏(TPM)

    取数游戏(TPM) 难度级别:D: 运行时间限制:1000ms: 运行空间限制:51200KB: 代码长度限制:2000000B 试题描述 给你一个n*n的格子的棋盘,每个格子里面有一个非负数.从中取 ...

  10. JavaScript权威指南学习笔记4

    今天看了第9.10.11章,感觉收获最大还是正则表达式那章节,不过这些不用太多脑子思考,问题用到了直接查书就可以了,下面分别总结一下: 第9章类和模块:分9节,前面8节都是在讲类相关的知识,最后一节讲 ...