0

我有一个对 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()作为 . 有任何想法吗?

4

1 回答 1

0

首先,您需要将 ajax 调用中的 contentType 更改为“json”。

然后尝试调用

alert(JSON.stringify(result));

看看它给了你什么。假设您正在正确构建 json 对象,它应该可以工作。还下载firebug并查看返回的内容。

编辑:

我不确定您的 uploadDocs 对象是什么样的,但请尝试执行

return Json(uploadedDocs);

在你的方法中。

JK,您正在使用 WebForms (?),因此要将其解析为 Json 对象,请参见此处

于 2012-11-02T15:34:20.423 回答