将对象从asp-c#传递到jquery
我想将一个对象从c#传递到jquery,但它不起作用。这是我的密码 c#: 我的结果是:MyArray没有任何内容 预期结果:将对象从asp-c#传递到jquery,c#,jquery,asp.net,json,C#,Jquery,Asp.net,Json,我想将一个对象从c#传递到jquery,但它不起作用。这是我的密码 c#: 我的结果是:MyArray没有任何内容 预期结果: myArray = [{ image: '/kazvan-1.jpg' },{ image: '/kazvan-2.jpg' },{ image: '/wojno-3.jpg' }] 您需要在服务中指定要返回的JSON,如下所示: [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 忽略返回的XML。尝试以下操作
myArray = [{ image: '/kazvan-1.jpg' },{ image: '/kazvan-2.jpg' },{ image: '/wojno-3.jpg' }]
您需要在服务中指定要返回的
JSON
,如下所示:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
忽略返回的XML
。尝试以下操作:
public class ImgLink
{
public string img;
}
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class ImgService : WebService
{
List<ImgLink> Imgs = new List<ImgLink>{
new ImgLink{img="/kazvan-1.jpg"},
new ImgLink{img="/kazvan-2.jpg"},
new ImgLink{img="/wojno-3.jpg"}
};
[WebMethod]
public List<ImgLink> GetAllImgs()
{
return Imgs;
}
}
你说了你的预期结果,但你的实际结果是什么?如果url真的是ImgService还是ImgService.asmx?最好的办法是从函数返回对象的JsonResult,那么该对象将在Javascript中可用;这是错误的。它应该是:myArray.push({“image”:car.img});这有用吗?我运行了你的代码,它运行得很好(除了+car.img部分。尽管如此,我仍然有一个包含3项的数组)查看Fiddler或Chrome developer tools Network tab或你最喜欢的网络流量工具,看看返回的响应是什么。您可能还想看看Dave Ward关于ASP.NET的“.d”的文章。我通常做的是下面的var cars=response.d | | response你没有对任何答案或评论做出回应。请回答-1.
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public class ImgLink
{
public string img;
}
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class ImgService : WebService
{
List<ImgLink> Imgs = new List<ImgLink>{
new ImgLink{img="/kazvan-1.jpg"},
new ImgLink{img="/kazvan-2.jpg"},
new ImgLink{img="/wojno-3.jpg"}
};
[WebMethod]
public List<ImgLink> GetAllImgs()
{
return Imgs;
}
}
function getImgs() {
var myArray = [];
$.ajax({
type: "POST",
url: "ImgService/GetAllImgs",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var cars = response.d;
$.map(cars, function (item) {//use .map method
myArray.push({ "image": +item.img });
});
alert("success");
},
failure: function (msg) {
alert("fail");
}
});
return myArray;
}