ajax调用WebService实现数据库操作
首先说下测试环境和思路:
前端收集数据转换成json格式传输到后端,处理并存入数据库
1.数据库操作:
[WebMethod]
public string InsertPoint(string data)
{
//解决跨域问题
//Context.Response.AddHeader("Access-Control-Allow-Origin", "*");
string database = "Data Source=.;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=password1633";
//string data = HttpContext.Current.Request["data"];
try
{ if (data.Equals("") || data == null)
{
return "data is null";
}
else
{
OverlaysPoint opoint = JsonConvert.DeserializeObject<OverlaysPoint>(data);// 将接收的参数data实例化为一个对象(方便操作),注意该类的变量名要和json的key值对应
/*foreach (Data_Opoint dtpoint in opoint.overlays)
{
sql = "insert into Map_Overlays(wf_pictureid,wf_picturename,wf_railid,wf_name,wf_location,wf_createtime,wf_pid,wf_lng,wf_lat) values('" + "123456789" + "','" + opoint.picturename + "','" + opoint.id + "','" + opoint.name + "','" + opoint.location + "','" + opoint.createime + "','" + dtpoint.pid + "','" + dtpoint.lng.ToString() + "','" + dtpoint.lat.ToString() + "')";
ExecuteUpdate(sql, database); }*/
string[] xyArray = opoint.position.Split(new string[] { "(", ",", ")" }, StringSplitOptions.RemoveEmptyEntries); //处理json字符串
//执行sql语句
string sql = "insert into map_img_points(miid,pointtype,pointid, pointcode, positionx, positiony, pointinfo) values ('地图id', '" + opoint.point_type + "', '" + opoint.point_bm + "','" + opoint.point_code + "','" + xyArray[] + "','" + xyArray[] + "', '" + opoint.point_info + "')";
executeUpdate(sql, database);
return "success"; }
}
catch (NullReferenceException e)
{
return e.StackTrace;
}
}
Data Source : 一个点默认为本地数据库,其他数据库填写相应ip ;
Initial Catelog:是目标数据库名称
我们接收一个json数据,将其value填入一个实例化的类对象,通过这个类的实例化对象来使用它
OverlaysPoint opoint = JsonConvert.DeserializeObject<OverlaysPoint>(data);
根据json创建的OverPoint类:
public class OverlaysPoint
{
public string point_type;
public string point_bm;
public string point_code;
public string position;
public string point_info;
public string con_bussiness;
public string con_entity;
public string con_fields;
public string showpic;
public string showtext;
public string showdata;
public string create_time;
public string data_refresh_rate;
}
executeQuery和executeUpdate方法(可重用):
//对数据库操作
//用于查询
private DataTable executeQuery(string sqlStr, string sqlCon)
{
SqlConnection con = new SqlConnection(@sqlCon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlStr;
DataTable dt = new DataTable(); //实例化数据表
SqlDataAdapter msda;
msda = new SqlDataAdapter(cmd); //实例化适配器
msda.Fill(dt); //保存数据
con.Close();
return dt;
}
//用于增删改;
private int executeUpdate(string sqlStr, string sqlCon)
{
SqlConnection con = new SqlConnection(@sqlCon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlStr;
int iud = ;
iud = cmd.ExecuteNonQuery();
con.Close();
return iud;
}
要使用JsonConvert需要引入外部依赖包 Newtonsoft.Json.dll 。
右键项目解决方案-添加引用-
2.ajax调用:
var jsonOverlays = JSON.stringify(data.field).replace(/\"/g,"'");// 将json数据的双引号替换为单引号
$.ajax({
type:"POST",
contentType: "application/json; charset=utf-8",
url:"http://192.168.21.1:7777/WebService1.asmx/InsertPoint",
data: "{\"data\":\"" + jsonOverlays + "\"}", //这是post请求要传递的参数
dataType: 'json', //预期返回类型
success: function(result){ //回调函数
layer.msg('ajax调用成功' + result.d);
console.log(result.d);
},
error: function (data) {
//200的响应有可能被认为error, responseText中没有Message部分
alert('error');
},
complete: function (data) {
; //after success ot error
}
});
注意:1.双引号替换为单引号 2.构造data的参数
ps:报错:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
解决跨域问题:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Credentials" value="true"/>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
<add name="Access-Control-Allow-Origin" value="*"/>
</customHeaders>
</httpProtocol>
2019-1-22测试无误:
如果出错,注意查看浏览器端控制台报错(ajax出错)和vs输出窗口(c#方法出错)
ajax调用WebService实现数据库操作的更多相关文章
- 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 ...
- Ajax调用WebService(一)
Ajax调用WebService(一) http://www.cnblogs.com/leslies2/archive/2011/01/26/1934889.html 分类: Ajax 使用技术 We ...
- 使用ajax调用webservice加载table
写了个ajax调用webservice动态加载表格的案例 不废话直接上代码 webservice代码: /// <summary> /// 首页显示会员信息 /// </summar ...
- AJAX 调用WebService 、WebApi 增删改查
WebService 页面: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 3 ...
- AJAX 调用WebService 、WebApi 增删改查(笔记)
经过大半天努力,终于完成增删改查了!心情有点小激动!!对于初学者的我来说,一路上都是迷茫,坑!!虽说网上有资料,可动手起来却不易(初学者的我).(苦逼啊!) WebService 页面: /// &l ...
- Jquery ajax调用webservice总结
jquery ajax调用webservice(C#)要注意的几个事项: 1.web.config里需要配置2个地方 <httpHandlers> <remove verb ...
- Ajax调用WebService
前台代码: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1 ...
- Jquery Ajax 调用 WebService
原文:http://www.cnblogs.com/andiki/archive/2010/05/17/1737254.html jquery ajax调用webservice(C#)要注意的几个事项 ...
- ajax调用webservice服务
ajax调用是 html方向调用的, 而sqlconnection是 java代码调用的,本质差不多 <html> <head> <title>通过ajax调用we ...
随机推荐
- SpringBoot 常用注解
@SpringBootApplication 这个配置等同于:@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三个配置. @Ena ...
- leetcode — longest-valid-parentheses
import java.util.Stack; /** * Source : https://oj.leetcode.com/problems/longest-valid-parentheses/ * ...
- samba企业级实战应用详解-技术流ken
1.简介 Samba是一套使用SMB(Server Message Block)协议的应用程序, 通过支持这个协议, Samba允许Linux服务器与Windows系统之间进行通信,使跨平台的互访成为 ...
- Spring Cloud Config采用Git存储时两种常用的配置策略
由于Spring Cloud Config默认采用了Git存储,相信很多团队在使用Spring Cloud的配置中心时也会采用这样的策略.即便大家都使用了Git存储,可能还有各种不同的配置方式,本文就 ...
- IntelliJ IDEA为类和方法自动添加注释
1.为类添加自动注释模版 File-->Settings-->Editor-->File and Code Templates /** * @author :mmzs * @date ...
- 我的IdentityServer目录
概念部分 理解oauth协议 理解什么是claim 学习Identity Server 4的预备知识 Open ID Connect(OIDC)在 ASP.NET Core中的应用 操作部分 入门: ...
- CentOS 7.4 64位安装配置MySQL8.0
第一步:获取mysql YUM源 进入mysql官网获取RPM包下载地址 https://dev.mysql.com/downloads/repo/yum/ image.png 点击下载 im ...
- SqlServer中循环和条件语句
if语句使用示例 declare @a int set @a=12 if @a>100 begin ...
- mybatis_13一级缓存
1. Mybatis的缓存理解 Mybatis的缓存,包括一级缓存和二级缓存,一级缓存是默认使用的.二级缓存需要手动开启. 一级缓存指的就是sqlsession,在sqlsession中有一个数据区域 ...
- Gvim 和vim 有什么区别
Gvim 和vim 有什么区别 Gvim是windows的 vim是linux的黑色的命令符 Gvim是单独的窗口下的vim,像notepad一样. vim就是在黑乎乎的cmd窗口下的编辑器.wind ...