我对Web服务进行了ajax调用,我想将一些JSON返回给视图。但是现在,如果我提醒通话结果,我会得到“对象文档”。我尝试改变内容类型,但没有骰子。这是当前状态下的ajax调用:
$.ajax({
type: "GET",
url: "services/offerService.asmx/getUploadedDocs",
contentType: 'text/html',
data: {offerID : offerId},
success: function(result) {
$.each(result, function(index) {
alert(result.toString());
$(element).closest('ul.uploadedDocs').append('<li id="uploadedDoc-'+(index+"") + '" class = "uploadedDocument"><span id="uploadedDocTitle">Title: '+ result["title"] + '</span><span id="uploadedDocUploadedBy>Uploaded By: ' + result["uploadedBy"] + '</span></li>');
});
}
});
这是网络方法:
[WebMethod]
public object getUploadedDocs(string offerID)
{
string sql = "SELECT * FROM [dbo].[uploaded_documents] WHERE primary_offer_id = @offerId";
IList<UploadedDocument> uploadedDocs = new List<UploadedDocument>();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["production"].ToString()))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@offerId", SqlDbType.Int);
cmd.Parameters["@offerId"].Value = offerID;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
adapter.Dispose();
uploadedDocs = dt.ToList<UploadedDocument>();
}
StringBuilder json = new StringBuilder();
json.Append("{");
int count = 1;
foreach (UploadedDocument doc in uploadedDocs)
{
json.Append("{doc"+count.ToString()+":"+"{\"title\": " + doc.docTitle + ", \"uploadedBy\": " + doc.uploadedBy + ", \"uploadDate\": " + doc.uploadDate.ToLongDateString() + "},");
}
if(json.ToString().Contains(","))
json = json.Remove(json.ToString().LastIndexOf(','), 1);
json.Append("}");
return json.ToString();
}
我可能会以object()
的形式将其发回,但我更愿意将其保留为字符串并将其解析为JSON。有任何想法吗?