问题描述
我试图将json对象从Web服务(ASP.NET WebForms应用程序)返回到Ajax成功响应中。尽管数据是通过Web服务返回的,但没有数据传递给Ajax响应。
这是WebService:
[WebMethod]
public List<Images> GetimageObj()
{
List<Images> all = new List<Images>();
Images infoObjs = new Images();
ImageLoading iload = new ImageLoading();
DataTable dtimages = iload.GetData();
foreach (DaTarow row in dtimages.Rows)
{
infoObjs.ID = Convert.ToInt32(row["FILE_ID"].ToString());
Byte[] bytes = ((Byte[])row["THUMBNAIL_CONTENT"]);
infoObjs.ImageURI = iload.Getimage(bytes);
all.Add(infoObjs);
}
return all;
}
public class Images
{
public List<Images> imgObjs;
public string ImageURI;
public int ID;
}
这是Ajax回调函数:
function AjaxCall() {
$(document).ready(function () {
var dataArr = [];
$.ajax({
url: '../WebService1.asmx/GetimageObj',method: 'post',contentType: 'application/json;charset=utf-8',dataType: 'json',data: "{'aray':" + JSON.stringify(dataArr) + "}",success: function (response) {
//No data is making it here:
var getData = JSON.parse(response.d);
alert(getData);
},error: function (err) {
alert(err);
}
});
});
}
更新:@Julian的答案解决了我的问题。但是,我必须将以下内容添加到我的webconfig中,以容纳来自编码图像URI的大数据:
<system.web.extensions>
<scripting>
<webServices>
<!-- Update this value to change the value to a larger value that can accommodate your JSON Strings -->
<jsonSerialization maxJsonLength="86753090" />
</webServices>
</scripting>
</system.web.extensions>
解决方法
尝试返回string
,但是使用Json.NewtonSoft
库以JSON序列化对象。
还要在要从Ajax使用的服务上添加[ScriptService]
标签:
C#代码:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public string GetImageObj()
{
List<Images> all = new List<Images>();
Images infoObjs = new Images();
ImageLoading iload = new ImageLoading();
DataTable dtImages = iload.GetData();
foreach (DataRow row in dtImages.Rows)
{
infoObjs.ID = Convert.ToInt32(row["FILE_ID"].ToString());
Byte[] bytes = ((Byte[])row["THUMBNAIL_CONTENT"]);
infoObjs.ImageURI = iload.GetImage(bytes);
all.Add(infoObjs);
}
return JsonConvert.SerializeObject(all,Formatting.Indented);
}
}
AJAX代码:
<script type="text/javascript">
$(document).ready(function () {
var dataArr = [];
$.ajax({
url: '../WebService.asmx/GetImageObj',method: 'POST',contentType: 'application/json; charset=utf-8',dataType: 'json',data: "{}",success: function (response) {
//No data is making it here:
var getData = JSON.parse(response.d);
console.log(getData);
},error: function (err) {
console.log(err);
}
});
});
</script>