我正在获取jQuery AJAX调用的null / undefined响应。我试图将数据绑定到asp.net webforms中的Jquery Data表。当我尝试解析数据时,它在位置1错误的JSON中给出了一个意外的令牌o。我怀疑问题可能与JSON数据有关,但我已在JSONlint.com验证了json输出。 它必须是我一些愚蠢的错误,但我无法弄明白,我浪费了几个小时来排除故障。
jQuery Ajax调用
username
的WebMethod
pass
JSON
<script type="text/javascript">
$(function () {
$('#ShowData').click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/fetchDetails',
dataType: 'json',
data: "{'JobID':'" + $('#txtJobID').val() + "'}",
success: function (response) {
//var d = JSON.parse(data);
var data = response.d;
alert(typeof (data)); //gives out object
alert(response.d); //gives out null
$('#tblBasicInfo').dataTable({
paging: false,
data: data,
columns: [
{ 'data': 'JobId' },
{ 'data': 'UserId' },
{ 'data': 'UserName' },
{ 'data': 'Cas' },
{ 'data': 'Question' },
{ 'data': 'Language' },
{ 'data': 'Appl' },
]
});
},
error: function (xhr, ajaxoptions, thrownError) {
alert(xhr.responseText);
console.log(xhr.responseText);
console.log(xhr.responseJSON);
}
});
});
});
</script>
答案 0 :(得分:0)
只需确保在您的代码中实现以下几点,然后它就会像它应该的那样工作。在$('#tblBasicInfo').DataTable({
void
。
您需要从Web方法fetchDetails
返回C#对象。fetchDetails
方法。我已经删除了所有的
fetchDetails方法中的序列化代码不需要。
只需从Web方法返回类的C#对象。因此,在您的情况下,在方法fetchDetails
中定义此类的实例。
工作类
public class Job {
public int JobId {get;set;}
public string UserId {get;set;}
public string UserName {get;set;}
public int Cas {get;set;}
public string Question {get;set;}
public string Language {get;set;}
public int Appl {get;set;}
}
fetchDetails方法返回作业类型
[System.Web.Services.WebMethod]
public static Job fetchDetails(string JobID)
{
var conn = System.Configuration.ConfigurationManager.ConnectionStrings["Connection"];
SqlConnection con = new SqlConnection(conn.ToString());
String query = "Select TOP 1 * FROM TAble where Jobid =@JobID";
DataTable dtBasicInfo = new DataTable();
SqlCommand a = new SqlCommand(query, con);
a.Parameters.AddWithValue("@JobID", Int32.Parse(JobID));
con.Open();
SqlDataAdapter da = new SqlDataAdapter(a);
da.Fill(dtBasicInfo);
SqlDataReader value = a.ExecuteReader();
con.Close();
//WRITE CODE to populate a Job object
Job job = new Job();
//set properties of job object before returning it as in code below
If (dtBasicInfo. Rows. Count > 0)
{
job.JobId = Int32.Parse(JobID);
job.UserId = dtBasicInfo.Rows[0]["UserId"].toString();
job.UserName = dtBasicInfo.Rows[0]["UserName"].toString();
}
return job;
}