在 jQuery 中调用 AJAX 函数后如何使用 JSON 数据
使用此代码:
$("#mybutton").click(function(){
$.ajax({
url: '/Member/GetPinPoints/@Model.Id',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
});
我收到一个如下所示的 JSON 对象:
[{"Position":1,"Top":182,"Left":20,"Height":73,"Width":90},{"Position":2,"Top":69,"Left":103,"Height":98,"Width":1}]
如何迭代此数据,假设我是否想提醒每个单独的值?
With this code:
$("#mybutton").click(function(){
$.ajax({
url: '/Member/GetPinPoints/@Model.Id',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
});
I am receiving a JSON object that looks like this:
[{"Position":1,"Top":182,"Left":20,"Height":73,"Width":90},{"Position":2,"Top":69,"Left":103,"Height":98,"Width":1}]
How can I iterate through this data, lets say if i wanted to alert each separate value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
普通的旧 JavaScript:
和 jQuery:
您需要在嵌套循环中进行迭代,因为您需要遍历数组中的所有元素,并且对于每个数组元素,遍历所有属性。
Plain old JavaScript:
And jQuery:
You need to iterate in a nested loop since you need to go over all elements in the array and for each array element, go over all properties.
前面的例子可以工作,但它们很幼稚。不擅长编码的示例只会循环遍历数组,这不是很健壮。
假设您在代码隐藏方法中返回键/值对,并且您希望能够根据需要分离这些数据来使用。你就从这个开始吧。
现在我们可以通过 jQuery Ajax 访问它,如下所示:
注意我如何创建一个名为 resp 的变量来保存 msg.d。然后我可以使用 resp.ReturnedDictionaryKey。上面我使用了使用过的代码和过期时间。我可以随意使用它们。
The previous examples will work, but they are naive. No good at coding's example will just loop through an array, which isn't very robust.
Let's pretend that you return key/value pairs in your code behind method and you want to be able to pick apart this data to use however you want. You start with this.
Now we can access it via jQuery Ajax like so:
Notice how I created a variable to hold msg.d, called resp. I can then use resp.ReturnedDictionaryKey. Above I used used code and expiredate. I can use them however I please.
试试这个。
Try this.