目前我有一个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);
}
});
});
});
我需要能够做类似警报的事情(drugQuiz.drugQuestions [0] .DrugId);
答案 0 :(得分:3)
循环返回的JSON并将每个项目推送到JavaScript数组中,如下所示:
success: function (data) {
$.each(data.d, function(i, item) {
drugQuiz.drugQuestions.push(item);
});
},
如果您想使用parseJSON()
执行此操作,请尝试以下操作:
success: function (data) {
var jsonData = JSON.parse(data.d);
for (var i in jsonData.drugQuestions) {
var question = jsonData.drugQuestions[i];
}
},
注意:我不确定JSON对象的名称,我猜测drugQuestions
是传回的drugQuestion
个对象数组的名称,如果不是,则更改jsonData.
值以匹配您返回的JSON的结构。