从ashx处理程序

时间:2016-12-05 06:04:46

标签: jquery ashx

我无法将逗号分隔的字符串拆分为数组。在我的ashx处理程序页面中,我的字符串如下所示:

context.Response.Write(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9} ", BusProfileID, BusinessName, BusinessPhone, BusinessEmail, BusinessAddress, BusinessCity, BusinessState, BusinessZip, BusinessWebsite, BusinessCategory));

当我尝试做一个数组时,结果不显示。

   <script>
        $(document).ready(function () {
            $('#ContentPlaceHolder1_businessSelect').change(function () {
                $.ajax({
                    contentType: "text/html; charset=utf-8",
                    data: "ID=" + $('#ContentPlaceHolder1_businessSelect').val(),
                    url: "getBusValue.ashx",
                    dataType: "text",
                    success: function (data) {
                    var vardata = JSON.stringify(data)
                    var arr = vardata.split(',')
                    $("#ContentPlaceHolder1_BusProfileID").val(arr[0]);
                    $("#ContentPlaceHolder1_BusinessName").val(arr[1];
                    $("#ContentPlaceHolder1_BusinessPhone").val(arr[2]);
                    $("#ContentPlaceHolder1_BusinessEmail").val(arr[3]);
                    $("#ContentPlaceHolder1_BusinessAddress").val(arr[4]);
                    $("#ContentPlaceHolder1_BusinessCity").val(arr[5]);
                  $("#ContentPlaceHolder1_BusinessState").val(arr[6]).prop('selected',true);
                    $("#ContentPlaceHolder1_BusinessZip").val(arr[7]);
                    $("#ContentPlaceHolder1_BusinessWebsite").val(arr[8]);
                   $("#ContentPlaceHolder1_BusinessCategory").val(arr[9]).prop('selected', true);
                    }
                });
            });
        });
    </script>

这是我的ashx页面:

   public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        string ID = context.Request.QueryString["ID"];
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader reader;
        string connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
        conn = new SqlConnection(connectionString);
        comm = new SqlCommand("SELECT BusProfileID, BusinessName, BusinessPhone, BusinessEmail, BusinessAddress, BusinessCity, BusinessState, BusinessZip, BusinessWebsite, BusinessCategory FROM [BusProfile] WHERE BusinessName = @BusinessName", conn);
        comm.Parameters.Add("@BusinessName", System.Data.SqlDbType.VarChar);
        comm.Parameters["@BusinessName"].Value = ID;
        try
        {
            conn.Open();
            reader = comm.ExecuteReader();
            if (reader.Read())
            {
                string BusProfileID = reader["BusProfileID"].ToString();
                string BusinessName = reader["BusinessName"].ToString();
                string BusinessPhone = reader["BusinessPhone"].ToString();
                string BusinessEmail = reader["BusinessEmail"].ToString();
                string BusinessAddress = reader["BusinessAddress"].ToString();
                string BusinessCity = reader["BusinessCity"].ToString();
                string BusinessState = reader["BusinessState"].ToString();
                string BusinessZip = reader["BusinessZip"].ToString();
                string BusinessWebsite = reader["BusinessWebsite"].ToString();
                string BusinessCategory = reader["BusinessCategory"].ToString();

                context.Response.Write(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9} ", BusProfileID, BusinessName, BusinessPhone, BusinessEmail, BusinessAddress, BusinessCity, BusinessState, BusinessZip, BusinessWebsite, BusinessCategory));
            }
            reader.Close();
        }

        finally
        {
            conn.Close();
        }
    }

这是成功后文本框中数据的样子:

8,My Business Inc,(702) 555-1212,123@aol.com,555 anywhere street,Los Angeles,California,44502,google.com,Hotel & Travel

2 个答案:

答案 0 :(得分:1)

以下是代码的演示。

var string = "8,my business inc,(702) 555-1212,123@aol.com,555 anywhere street,Los Angeles,california,44502,google.com,hotel and ttravel";

var stringArray = string.split(',');

console.log(stringArray);

结果如下:

[&#34; 8&#34;,&#34; my business inc&#34;,&#34;(702)555-1212&#34;,&#34; 123@aol.com& #34;,&#34; 555任何街道&#34;,&#34;洛杉矶&#34;,&#34;加利福尼亚&#34;,&#34; 44502&#34;,&#34; google.com& #34;,&#34;酒店和ttravel&#34;]

console.log(xm[5]);

输出: 洛杉矶

如果成功获得的数据是一个字符串,那么可能就是流程如何......

我认为您编写的代码中没有任何错误。

如果数据不是字符串,那么

执行var string = "" + data;将其转换为字符串。

答案 1 :(得分:0)

这是一个lenthy帖子,但我希望它可以帮助你。

第一部分是使用两种不同方式的Web服务,一种是作为Web服务,另一种是作为列表并将其序列化的常规类。

webservice1.asmx:

    namespace WebApplication1
    {    // a class in context with how the data are is being used
        [Serializable]
        public class select2
        {
            public String id { get; set; }
            public String text { get; set; }
            public select2(String code, String name)
            {
                this.id = code;
                this.text = name;
            }
        }
        // input parms not used but to show concept
        public struct parameters
        {
            string parm1;
            string parm2;
        }

        /// <summary>
        /// Summary description for WebService1
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        [System.Web.Script.Services.ScriptService]
        public class WebService1 : System.Web.Services.WebService
        {

            [WebMethod]
            public string GetAList(String s)
            {
                System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
                parameters parms = ser.Deserialize<parameters>(s);
                return makelist();
            }

             // return a list of serialized codes and countries
            public String makelist()
            {
                List<select2> list = new List<select2>();

                list.Add(new select2("AI", "Anguilla"));
                list.Add(new select2("AQ", "Antarctica"));
                list.Add(new select2("AG", "Antigua and Barbuda"));
                list.Add(new select2("AR", "Argentina"));
                list.Add(new select2("AM", "Armenia"));
                list.Add(new select2("AW", "Aruba"));
                list.Add(new select2("AU", "Australia"));
                list.Add(new select2("AT", "Austria"));
                list.Add(new select2("AZ", "Azerbaijan"));
                list.Add(new select2("BS", "Bahamas"));
                list.Add(new select2("BH", "Bahrain"));
                list.Add(new select2("BD", "Bangladesh"));
                list.Add(new select2("BB", "Barbados"));
                list.Add(new select2("BY", "Belarus"));
                list.Add(new select2("BE", "Belgium"));
                list.Add(new select2("BZ", "Belize"));
                // did it this way to show you which to use
                System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
                String jsonList = ser.Serialize(list);
                return jsonList;
            }
        }
    }

下一节是后面的代码部分:

    namespace WebApplication1
    {

        public partial class select2 : System.Web.UI.Page
        {
            public String JsonCountries { get
            {
                    // use the web service as a regular class to return the serialized list
                return (new WebService1()).makelist();
            } }

            protected void Page_Load(object sender, EventArgs e)
            {

            }
        }
    }

最后是一个aspx页面,它将一个select2框从ajax调用填充到web方法,而第二个select 2则是由后面的代码放入的数据填充的。它与你正在做的有点不同,但概念证明已经到位,应该给你足够的信息。

       $(document).ready(
                function () {
                    // property on code behnd
                    var cblist = <%=JsonCountries%>;
                    $("#sel3").select2({  data:cblist });

                    parms = JSON.stringify({ parm1: "one", parm2: "two" });

                        $.ajax({
                            url: "WebService1.asmx/GetAList",
                             data: JSON.stringify( {s:parms}),
                            type: 'post',
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",

                            success: function (data, status) {
                                var contries = JSON.parse(data.d);
                                $("#sel2").select2({ data: contries });
                            },
                            error: function (one, two) {
                                debugger;
                            }
                        });

                }
            );
        </script>
    </head>
        <body>
           <div>
               <p>populated from ajax</p>
               <select id="sel2"></select>
            </div>

            <div>
                <p>populated from code behind</p>
                <select id="sel3"></select>
            </div>
        </body>
    </html>