为什么当我试图从asp.net web服务返回的值中获取数据时,jquery中出现了未定义的情况

本文关键字:数据 获取 jquery 情况 未定义 asp net web 为什么 返回 服务 | 更新日期: 2023-09-27 18:00:30

//Web服务代码webService.asmx这是从web服务获取数据的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Configuration;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 WebService : System.Web.Services.WebService
{
public WebService()
{
    //Uncomment the following line if using designed components 
    //InitializeComponent(); 
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getTableData()
{
    SqlConnection _connect = new SqlConnection();
    try
    {
        _connect.ConnectionString =     ConfigurationManager.ConnectionStrings["ERPV2ConnectionString"].ToString();
        _connect.Open();
        string query = "Select FirstName [Name], EmpCode [Code] From payroll.tblEmpMaster where EmpNo between 12 And 15";
        SqlCommand cmd = new SqlCommand(query, _connect);
        string strquery = null;
        cmd.ExecuteNonQuery();
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        _connect.Close();
        strquery = DataSetToJSON(ds);
        return strquery;

    }
    catch (Exception ex)
    {
        _connect.Close();
        throw ex;
    }
}
public string DataSetToJSON(DataSet ds)
{
    StringBuilder JsonString = new StringBuilder();
    DataTable dt = ds.Tables[0];
    //Exception Handling
    if (dt != null && dt.Rows.Count > 0)
    {
        JsonString.Append("[ ");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            JsonString.Append("{ ");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                if (j < dt.Columns.Count - 1)
                {
                    JsonString.Append("'"" + dt.Columns[j].ColumnName.ToString() +
                          "'":" + "'"" +
                          dt.Rows[i][j].ToString() + "'",");
                }
                else if (j == dt.Columns.Count - 1)
                {
                    JsonString.Append("'"" +
                       dt.Columns[j].ColumnName.ToString() + "'":" +
                       "'"" + dt.Rows[i][j].ToString() + "'"");
                }
            }
            /*end Of String*/
            if (i == dt.Rows.Count - 1)
            {
                JsonString.Append("} ");
            }
            else
            {
                JsonString.Append("}, ");
            }
        }
        JsonString.Append("]");
        return JsonString.ToString();
    }
    else
    {
        return null;
    }

}
}
<!DOCTYPE html>
<html>
<head>
<script   src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">       </script>
<script>
    $(document).ready(function () {
        $("button").click(function () {
            $.ajax({ type: "POST",
                contenttype: "application/json; charset=utf-8",
                data: "{null}",
                url: "WebService.asmx/getTableData",
                dataTyp: "json",
                success: function (data) {
                    var xml = $(data);
                    $("#table1").append("<tr><th>name</th><th>code</th></tr>");
                    $.each(xml, function (i, v) {
                        //                        $('#p1').html(v.city);
                        $("#table1").append("<tr><td>" + v.name + "</td>  <td>" + v.code + "</td></tr>");
                    });
                },
                error: function (err) {
                    alert(err);
                }
            });
        });
    });

</script>

邮寄

我在这个代码中做错了什么?

为什么当我试图从asp.net web服务返回的值中获取数据时,jquery中出现了未定义的情况

您的代码中有两个感兴趣的片段:

return JsonString.ToString();

var xml = $(data);

他们正在尝试做不同的事情。web服务正在返回JSON数据,但您正试图将其解析为XML数据。您需要将服务器输出解析为JSON数据:

var xml = $.parseJSON(data);

现在,您可以进入并检查对象,看看需要迭代什么才能得到所需的结果。在Chrome上,您可以使用控制台轻松检查:

console.log("xml: %o", xml);

尝试使用data.d

 success: function (data) {
   var xml = data.d;
   alert(xml);
}

 public class UserInfo
{
        public string Name;
        public string Code;
        public string Salary;
}

[WebMethod]
public List<UserInfo> getTableData()
{
    SqlDataReader dr;
    List<UserInfo> UserInfo = new List<UserInfo>();
 
    using (SqlConnection con = new SqlConnection(conn))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "ProcedureName";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = con;
            con.Open();
            dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    string Name = dr["Name"].ToString();
                    string Code = dr["Code"].ToString();
                    string makingyear = dr["carYear"].ToString();
                     UserInfo.Add(new usr {Name = Name, Code = Code });
                }
            }
        }
    }
    return UserInfo;
}

$("#button").on("click", function (e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
         data: "{null}",
        url: "WebService.asmx/getTableData",
        data: jsonData,
        contentType: "application/json; charset=utf-8",
        dataType: "json", // dataType is json format
        success: OnSuccess,
        error: OnErrorCall
    });
   
    function OnSuccess(response) {
      console.log(response.d)
    }
    function OnErrorCall(response) { console.log(error); }
    });