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 ...
随机推荐
- Unity3D热更新之LuaFramework篇[02]--用Lua创建自己的面板
在上篇文章 Unity3D热更新之LuaFramework篇[01]--从零开始 中,我们了解了怎么获得一个可用的LuaFramework框架. 本篇将我会先介绍一下如何配置Lua开发环境,然后分析在 ...
- vue-08-axios-get-post-跨域
1, 安装 cnpm install axios --save 2, 在main.js中引入 import Axios from 'axios' // 挂在在Vue上Vue.prototype.$ax ...
- leetcode — text-justification
import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * * Source : https:/ ...
- 阿里云CentOS安装配置Python3.7及pip3
一.安装Python3.7 安装依赖包 yum install openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqli ...
- python使用多进程
python多线程适合IO密集型场景,而在CPU密集型场景,并不能充分利用多核CPU,而协程本质基于线程,同样不能充分发挥多核的优势. 针对计算密集型场景需要使用多进程,python的multipro ...
- ACM菜鸡退役帖——ACM究竟给了我什么?
这个ACM退役帖,诸多原因(一言难尽...),终于决定在我大三下学期开始的时候写出来.下面说两个重要的原因. 其一是觉得菜鸡的ACM之旅没人会看的,但是新学期开始了,总结一下,只为了更好的出发吧. 其 ...
- shell脚本示例:批量比较多个文件的内容是否相同
bash&shell系列文章:http://www.cnblogs.com/f-ck-need-u/p/7048359.html 要比较两个文件的内容是否完全一致,可以简单地使用diff命令. ...
- 学会这个删库再也不用跑路了~ --技术流ken
前言 相信每一个学IT的人或多或少都听说过从删库到跑路这个梗~下图也是在各种交流群屡禁不止,新人听着也是瑟瑟发抖. 人们茶余饭后,街头巷角难免要问... 下面技术流ken就教给各位新手们一招删库再也不 ...
- [转]Ubuntu18.04下使用Docker Registry快速搭建私有镜像仓库
本文转自:https://blog.csdn.net/BigData_Mining/article/details/88233015 1.背景 在 Docker 中,当我们执行 docker pull ...
- Easyui input 取值跟赋值
var val = $("#id").textbox('getValue') //取值 $("#id").textbox('setValue','text') ...