Ajax请求Web方法返回文档对象而不是文本或JSON

时间:2012-11-02 15:25:14

标签: c# ajax json jquery webmethod

我对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。有任何想法吗?

1 个答案:

答案 0 :(得分:0)

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

然后尝试拨打

alert(JSON.stringify(result));

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

编辑:

我不确定您的uploadedDocs对象是什么样子但是尝试

return Json(uploadedDocs);

在你的方法中。

JK你正在使用WebForms(?)所以要将它解析为Json对象,请参阅here