ajax调用webservice(二) 跨域。

所需工具与项目结构同(一)。

service.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 = "selectbyid")]

        public void getDBTableInfos(string EnterpriseCode)
        {
            HttpContext.Current.Response.ContentType = "application/json;charset=utf-8";  
            string jsonCallBackFunName = string.Empty;  
            jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"].ToString();  
            string jsonStr=string.Empty;
            CarUsing caru = new CarUsing();
            string sql = "select * from CarUsing where cuid =@cuid";
            SqlParameter para = new SqlParameter("@cuid", Convert.ToInt32(EnterpriseCode));
            using (SqlDataReader dr = SqlHelper.ExecuteReader(sql, CommandType.Text, para))
            {
                while (dr.Read())
                {
                    caru = new CarUsing(
                         Convert.ToInt32(dr["cuid"]),
                         dr["carUsing"].ToString()
                        );
                }
            }
            jsonStr = JsonConvert.SerializeObject(caru);
            HttpContext.Current.Response.Write(string.Format("{0}({1})", jsonCallBackFunName, new JavaScriptSerializer().Serialize(jsonStr)));  
        }
        [WebMethod(Description = "测试selectall")]
        public void getDBTableInfos1()
        {
            HttpContext.Current.Response.ContentType = "application/json;charset=utf-8";
            string jsonCallBackFunName = string.Empty;
            jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"].ToString();
            string jsonStr = string.Empty;
            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);
                }
                jsonStr = JsonConvert.SerializeObject(CarUsings);
            }
            HttpContext.Current.Response.Write(string.Format("{0}({1})", jsonCallBackFunName, new JavaScriptSerializer().Serialize(jsonStr)));
        }

        [WebMethod(Description = "添加")]
        public void getDBTableInfos2(string cusing)
        {
            string result = "";
            HttpContext.Current.Response.ContentType = "application/json;charset=utf-8";
            string jsonCallBackFunName = string.Empty;
            jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"].ToString();
            string jsonStr = string.Empty;
            string sql = string.Format("insert into CarUsing values(@carUsing)");
            SqlParameter para = new SqlParameter("@carUsing", cusing);
            result = SqlHelper.ExecuteNonQuery(sql, CommandType.Text, para).ToString();
            jsonStr = JsonConvert.SerializeObject(result);
            HttpContext.Current.Response.Write(string.Format("{0}({1})", jsonCallBackFunName, new JavaScriptSerializer().Serialize(jsonStr))); 
        }
        [WebMethod(Description = "修改")]
        public void getDBTableInfos3(string cuid,string cusing)
        {
            string result = "";
            HttpContext.Current.Response.ContentType = "application/json;charset=utf-8";
            string jsonCallBackFunName = string.Empty;
            jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"].ToString();
            string jsonStr = string.Empty;
            string sql = string.Format("update CarUsing set carUsing =@carUsing where cuid=@cuid");
            SqlParameter[] paras = {
                                        new SqlParameter("@carUsing",cusing),
                                        new SqlParameter("@cuid", cuid)
                                   };
            result = SqlHelper.ExecuteNonQuery(sql, CommandType.Text, paras).ToString();
            jsonStr = JsonConvert.SerializeObject(result);
            HttpContext.Current.Response.Write(string.Format("{0}({1})", jsonCallBackFunName, new JavaScriptSerializer().Serialize(jsonStr)));
        }
        [WebMethod(Description = "删除")]
        public void getDBTableInfos4(string cuid)
        {
            string result = "";
            HttpContext.Current.Response.ContentType = "application/json;charset=utf-8";
            string jsonCallBackFunName = string.Empty;
            jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"].ToString();
            string jsonStr = string.Empty;
            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();
            jsonStr = JsonConvert.SerializeObject(result);
            HttpContext.Current.Response.Write(string.Format("{0}({1})", jsonCallBackFunName, new JavaScriptSerializer().Serialize(jsonStr)));
        }
    }
}
View Code


html中代码如下:

<!DOCTYPE html>

<html>

<head>

    <title>Index</title>
    <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnSubmit").click(function () {
                var EnterpriseCode = "1"; //企业代码               
                var dataStr = "EnterpriseCode=" + EnterpriseCode;
                $.ajax({
                    type: "get",
                    url: "http://localhost:22657/Service1.asmx/getDBTableInfos?jsoncallback?",
                    dataType: "jsonp",
                    jsonp: 'jsoncallback',
                    data: dataStr,
                    success: function (result) {
                        //返回结果
                        var str = result;
                        var jsonList = eval("(" + str + ")");
                        var html = "<table border=1 bordercolor=6d6d6d cellspacing = 1>";
                        html += "<tr backgroundcolor='yellow'><td>Id</td><td>用途</td><td>操作</td></tr>";
                        html += "<tr>";
                        html += "<td>" + jsonList.Cuid + "</td><td>" + jsonList.CareUsing + "</td><td><a href='javascript:;' onclick='UpdateInit(" + jsonList.Cuid + ")'>修改</a>&nbsp;<a href='javascript:;' onclick='if(confirm("确定删除嘛?")){Delete(" + jsonList.Cuid + ");}'>删除</a></td>";
                        html += "</tr>";
                        html += "</table>"
                        $("#div1").html(html);
                    },
                    error: function (result) {
                        alert("error");
                    }
                })
            });
            $("#btnSubmit1").click(function () {
                $.ajax({
                    type: "get",
                    url: "http://localhost:22657/Service1.asmx/getDBTableInfos1?jsoncallback?",
                    dataType: "jsonp",
                    jsonp: 'jsoncallback',
                    data: "{}",
                    success: function (result) {
                        var str = result;
                        var jsons = eval("(" + str + ")");
                        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>&nbsp;<a href='javascript:;' onclick='if(confirm("确定删除嘛?")){Delete(" + jsons[i].Cuid + ");}'>删除</a></td>";
                            html += "</tr>";
                        }
                        html += "</table>"
                        $("#div1").html(html);

                    },
                    error: function (result) {
                        alert("error");
                    }
                })
            });
            $("#btnSubmit2").click(function () {
                var carUsing = "测试测试1"; //企业代码               
                var dataStr = "cusing=" + carUsing;
                $.ajax({
                    type: "get",
                    url: "http://localhost:22657/Service1.asmx/getDBTableInfos2?jsoncallback?",
                    dataType: "jsonp",
                    jsonp: 'jsoncallback',
                    data: dataStr,
                    success: function (result) {
                        if (result = "1") {
                            alert("success");
                        }
                        else {
                            alert("fail");
                        }
                    },
                    error: function (result) {
                        alert("error");
                    }
                })
            });

            $("#btnSubmit3").click(function () {
                var carUsing = "测试测试"; //企业代码               
                var dataStr = "cuid=5&cusing=" + carUsing;
                $.ajax({
                    type: "get",
                    url: "http://localhost:22657/Service1.asmx/getDBTableInfos3?jsoncallback?",
                    dataType: "jsonp",
                    jsonp: 'jsoncallback',
                    data: dataStr,
                    success: function (result) {
                        if (result = "1") {
                            alert("success");
                        }
                        else {
                            alert("fail");
                        }
                    },
                    error: function (result) {
                        alert("error");
                    }
                })
            });

            $("#btnSubmit4").click(function () {
                var carUsing = "38";
                var dataStr = "cuid=" + carUsing;
                $.ajax({
                    type: "get",
                    url: "http://localhost:22657/Service1.asmx/getDBTableInfos4?jsoncallback?",
                    dataType: "jsonp",
                    jsonp: 'jsoncallback',
                    data: dataStr,
                    success: function (result) {
                        if (result = "1") {
                            alert("success!");
                        }
                        else {
                            alert("fail");
                        }
                    },
                    error: function (result) {
                        alert("error");
                    }
                })
            });
        });
    </script>
</head>

<body>
    <div>
        <input id="btnSubmit" type="button" value="selectbyId" />
        <input id="btnSubmit1" type="button" value="selectall" />
        <input id="btnSubmit2" type="button" value="Insert" />
        <input id="btnSubmit3" type="button" value="Update" />
        <input id="btnSubmit4" type="button" value="Delete" />
        <div id="div1"></idv>
    </div>
</body>

</html> 
View Code

 Note:如果读取的是access数据库,在发布后记得设置access的写入权限。否则无法读取数据。

原文地址:https://www.cnblogs.com/Jokers/p/3399758.html