让我想要与HTML元素上的值匹配的JSON响应,并将一个简单的字符串添加到HTML元素。
实施例: HTML
<div class="product-item" data-mydatavalue="EventOne">Hello this is my div for Event One<span class="maxCapacityForEvent"></span></div>
<div class="product-item" data-mydatavalue="EventTwo">Hello this is my div for Event Two<span class="maxCapacityForEvent"></span></div>
JSON
{"result":[{"EventName":"EventOne","MaxCapacity": 0},{"EventName":"EventTwo","MaxCapacity": 0}]}
我正在对我们的服务进行标准的jQuery AJAX调用并执行.each(),循环遍历JSON结果。 我想要做的是匹配EventName值和数据值匹配的每个HTML元素,以输出MaxCapacity
我的jQuery如下:
$.ajax({
url: "http://myservice.com/mycall",
type: "GET",
cache: false,
dataType: "json",
success: function (data) {
$.each(data, function (i, eventTypes) {
$.each(eventTypes, function(x, eventType) {
//NEED TO GET THE EVENT NAME FROM SERVICE TO MATCH THIS HTML ELEMENT - HOW DO I DO THIS?
if (eventType.EventName == $('.product-item').data("mydatavalue")){
$('.product-item').data("mydatavalue").find('.maxCapacityForEvent').text(eventType.Available);
}
});
});
},
error: function(xhr, error, data) {
console.log(xhr, error, data);
alert("An error occurred getting the Event Types");
}
});
这是我的JSBin链接 JSBIN
接受的答案
但我需要知道如何查看元素是否具有数据值但在JSON响应中是否存在。但我得到了全部或全部。
我目前的JS
$.ajax({
url: url,
type: "GET",
cache: false,
dataType: "json",
},
success: function (data) {
$.each(data.result, function (i, eventTypes) {
$('.product-item').each(function () {
if ($(this).attr('data-mydatavalue') == eventTypes.EventName) {
$(this).find('.maxCapacityForEvent').html(eventTypes.Available);
} else{
//This is giving filling in all elements with No Available if one of the
//.product-item elements don't have a data value.
$(this).find('.maxCapacityForEvent').html("Not Available");
}
});
});
答案 0 :(得分:2)
您可以轻松完成此操作,而无需迭代eventTypes
。
这是一个例子。
function doIterateJSON() {
var json = '[{"EventName":"EventOne","MaxCapacity": 0},{"EventName":"EventTwo","MaxCapacity": 0}]';
$.each($.parseJSON(json), function(key, value) {
$('.product-item').each(function() {
if ($(this).attr('data-mydatavalue') == value.EventName) {
$(this).find('.maxCapacityForEvent').html(value.MaxCapacity);
}
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button onclick="javascript:doIterateJSON();">
YEAH DO IT!
</button>
<div class="product-item" data-mydatavalue="EventOne">Hello this is my div for Event One<span class="maxCapacityForEvent"></span>
</div>
<div class="product-item" data-mydatavalue="EventTwo">Hello this is my div for Event Two<span class="maxCapacityForEvent"></span>
</div>
答案 1 :(得分:1)
你需要这样做
|Header 1| header 2| header 3| header 4|
|--------------------------------------|
| | | data1 | data1 |
|id1 | name1 | data2 | data2 |
| | | data3 | data3 |
|--------------------------------------|
| | | data1 | data1 |
|id2 | name2 | data2 | data2 |
| | | data3 | data3 |
|--------------------------------------|