Ajax调用webService(一) 不跨域。
生活随笔
收集整理的這篇文章主要介紹了
Ajax调用webService(一) 不跨域。
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
注:需要的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; }}} View CodeService1.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;}} } View Code注:在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:;' οnclick='UpdateInit(" + jsons[i].Cuid + ")'>修改</a>?<a href='javascript:;' οnclick='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 οnlοad="showAll()"><form id="form1" runat="server"><input type="button" value="添加車源用途" οnclick="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="隱藏" οnclick="CloseDiv()" /><input type="hidden" id="txtid" />用途:<input type="text" id="txtcarUsing" /><input type="button" value="添加" οnclick="InsertInfo()" /><input type="button" value="修改" οnclick="UpdateSend()" /></div></td></tr></table></div></form> </body> </html>
?運行界面如下:
轉載于:https://www.cnblogs.com/Jokers/p/3399742.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Ajax调用webService(一) 不跨域。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (C#)Windows Shell 编程
- 下一篇: 那些年我们排过的序之希尔排序