我遇到了一个错误,我希望这里有人可以帮助我,因为我一直试图找出错误的原因,太长了!
好的,我正在使用WCF以及AJAX和jQuery来访问名为Player
的类
这是带有相关OperationContract
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getplayers")]
[return: MessageParameter(Name = "Players")]
Player[] GetPlayersInTeam(int TeamId);
以下是实际的休息服务方法:
public Player[] GetPlayersInTeam(int teamId)
{
string connString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
try
{
conn.Open();
}
catch
{
}
List<Player> Players = new List<Player>();
string query = "SELECT * FROM Player WHERE TeamId = @TeamId";
SqlCommand command = new SqlCommand(query, conn);
command.Parameters.AddWithValue("@TeamId", teamId);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Player player = new Player(teamId, Convert.ToString(reader[2]),
Convert.ToString(reader[3]));
Players.Add(player);
}
return Players.ToArray();
}
return null;
}
}
以下是玩家类:
[DataContract(Name = "Player", Namespace = "")]
public class Player
{
// attributes
private int _teamId;
private string _playerName;
private string _position;
public Player() { }
public Player(int teamId, string playerName, string position)
{
_teamId = teamId;
_playerName = playerName;
_position = position;
}
[DataMember(Name = "teamId", Order = 1)]
public int TeamId
{
get { return _teamId; }
set { _teamId = value; }
}
[DataMember(Name = "playerName", Order = 2)]
public string PlayerName
{
get { return _playerName; }
set { _playerName = value; }
}
[DataMember(Name = "position", Order = 3)]
public string Position
{
get { return _position; }
set { _position = value; }
}
}
这是jQuery-Ajax请求:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var teamId = $.session.get("teamId");
$.ajax({
cache: false,
type: "POST",
url: "RestService.svc/getplayers",
data: '{ "teamId":"' + teamId + '"}',
contentType: "application/json; charset=utf-8",
success: function (json, status, req) {
var JSONReturn = json.Players;
if (JSONReturn != null) {
alert("picked up players");
}
else {
alert("error");
}
},
error: AjaxError
});
成功函数似乎总是返回null
,我不知道为什么。我基本上想要抓住所有具有相关teamId
的玩家,其中teamId
是会话字段。 teamId
字段工作正常并完美地返回当前teamId
,因此它与此无关。
但无论如何,任何帮助都会非常感激。我只是希望它是一个简单的错误,因为我疯了。 (这样的noob程序员)。
编辑:控制台日志功能显示了json成功函数内的 ajax请求包含Player类中的Players列表,但列表设置为null。CONSOLE.LOG
XHR finished loading: "http://localhost:54033/RestService.svc/getplayers". jquery.js:18
send jquery.js:18
b.extend.ajax jquery.js:18
(anonymous function) TeamSelection.aspx:24
c jquery.js:5
p.fireWith jquery.js:5
b.extend.ready jquery.js:5
H jquery.js:5
Object {Players: null}
(TeamSelection.aspx匿名函数是上面发布的ajax调用。你可以在底部看到,json显然包含一个名为Players的Object,但是等于null。
我无法弄清楚为什么会这样。我还添加了dataType但这没有任何影响。我很难过:(
由于