目前我有一个 AJAX 请求,它将运行以下 SQL 语句。
select top 1
DrugQuestionId
,DrugId
,DrugQuestion as DrugQuizquestion
,CorrectAnswer
,QuizQuestionTypeId
from DrugQuestions
并返回一个drugQuestion
对象,其属性列在 SQL Server 表中。
相关JS:
$(document).ready(function ()
{
$('#btnSubmit').click(function ()
{
$.ajax(
{
type: "POST",
url: "GetDrugQuiz.asmx/GenerateDrugQuestion",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
var drugQuestion = $.parseJSON(data.d);
//everything prints to the console correctly
console.log(drugQuestion.DrugQuestionId); //5 in this example
console.log(drugQuestion.DrugId);
console.log(drugQuestion.DrugQuizQuestion);
console.log(drugQuestion.CorrectAnswer);
console.log(drugQuestion.QuizQuestionTypeId);
},
error: function (xhr)
{
alert(xhr.status);
}
});
});
});
这很好用,给了我正在寻找的答案。在实践中,我需要一个drugQuiz
具有属性的对象,该属性是对象数组drugQuestion
。我使用以下 WebMethod 来尝试:
//this is questions, plural mean to populate an array with a length equal to the row count
//of the query
public string GenerateDrugQuestions()
{
var jss = new JavaScriptSerializer();
DrugQuiz qz = new DrugQuiz();
qz.PatientId = 123;
qz.DateTaken = DateTime.Now;
qz.DrugQuizId = 1;
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("select top 3 * from DrugQuestions", con))
{
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
DrugQuestion dq = new DrugQuestion();
dq.DrugQuestionId = (int)rdr["DrugQuestionId"];
dq.DrugId = (int)rdr["DrugId"];
dq.DrugQuizQuestion = rdr["DrugQuestion"].ToString();
dq.CorrectAnswer = rdr["CorrectAnswer"].ToString();
dq.QuizQuestionTypeId = (int)rdr["QuizQuestionTypeId"];
qz.DrugQuestions.Add(dq);
}
return jss.Serialize(qz);
}
}
}
因此,您可以看到 WebMethod 正在返回一个 JSON 字符串。当我在没有实际访问页面的情况下使用 WebMethod 并点击 Invoke 时,我得到了正确的字符串。我想不通的是如何填充数组drugQuestions
,这是一个drugQuiz
对象的属性。我需要对以下代码进行哪些更改以允许这种情况发生?
$(document).ready(function ()
{
var drugQuiz = {};
drugQuiz.drugQuestions = new Array();
$('#btnSubmit').click(function ()
{
$.ajax(
{
type: "POST",
url: "GetDrugQuiz.asmx/GenerateDrugQuestions",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
drugQuiz.drugQuestions.push($.parseJSON(data.d));
console.log(drugQuiz.drugQuestions.length);
console.log(drugQuiz.drugQuestions);
},
error: function (xhr)
{
alert(xhr.status);
}
});
});
});
我需要能够做类似的事情 alert(drugQuiz.drugQuestions[0].DrugId);