我遇到了一个错误,我希望这里有人可以帮助我,因为我一直在试图找出问题所在,好吧,太久了!
好的,我正在使用 WCF 以及 AJAX 和 jQuery 来访问一个名为Player
这是相关的 WCF 接口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
完美地返回了电流,因此与此无关。
但无论如何,任何帮助将不胜感激。我只是希望这是一个简单的错误,因为我快疯了。(这样的菜鸟程序员)。
编辑:控制台日志函数显示 ajax 请求的成功函数中的 json 包含来自 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 但这没有任何效果。我很难过:(
谢谢