// 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>
发送
我在这段代码中做错了什么?
答案 0 :(得分:0)
尝试使用data.d
success: function (data) {
var xml = data.d;
alert(xml);
}
查看此文章 Simple jQuery ajax JSON example in Asp.net c# with sql database
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); }
});
已经添加了一个非常好解释的 article link ,你必须检查,以便更好地了解它
答案 1 :(得分:0)
您的代码中感兴趣的两个snippits:
return JsonString.ToString();
和
var xml = $(data);
这些都试图做不同的事情。 Web服务正在返回JSON数据,但您尝试将其解析为XML数据。您需要将服务器输出解析为JSON数据:
var xml = $.parseJSON(data);
现在,您可以进入并检查对象,以查看需要迭代以获得所需结果的内容。在Chrome上,您可以使用控制台轻松检查:
console.log("xml: %o", xml);