2016-12-05 10 views
3

У меня возникла проблема с разделением строки с разделителями-запятыми на массив. На моей странице обработчика ashx моя строка выглядит так:JQuery разделенная запятая, ограниченная от ashx handler

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,[email protected],555 anywhere street,Los Angeles,California,44502,google.com,Hotel & Travel 
+1

Можете ли вы показать результат выражения 'var arr = data.split (',')'? – Satpal

+0

вы просто записываете всю строку в элемент ... –

+0

Comma разделяет их, как это прокомментировал @Satpal, используя data.split (',') для этого. –

ответ

0

это является lenthy пост, но я надеюсь, что это помогает вы.

Первая часть - это веб-сервис, который используется двумя разными способами, одним из способов использования веб-сервиса, а другой - обычным классом, который делает список и сериализует его.

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, что населяет один ВЫБ.2 окно с вызова Ajax для веб-метода и второй выбор 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> 
1

Настоящая демонстрация кода.

var string = "8,my business inc,(702) 555-1212,1[email protected],555 anywhere street,Los Angeles,california,44502,google.com,hotel and ttravel"; 

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

console.log(stringArray); 

Результат здесь:

[ "8", "мой бизнес вкл", "(702) 555-1212", "[email protected]", «555 где-нибудь улица», "Лос-Анджелес", "Калифорния", "44502", "google.com", "отель и ttravel"]

console.log(xm[5]); 

выход: Лос-Анджелес

, если данные, которые вы получите в случае успеха является строкой, то, возможно, вот как поток выходит .....

Я не думаю, что есть какая-либо ошибка в коде, который вы написали.

, если данные не является строкой, то

сделать var string = "" + data;, чтобы преобразовать его в строку.

+1

Я добавил var vardata = JSON.stringify (данные) в код, и он работает сейчас. –

+0

Вероятно, потому что это была не строка .... –

+0

В этом случае JSON.Stringify (data) просто преобразует данные в строковый тип данных. –