问题
These are the key/values in JSON
[
{
"country":"First",
"coupon":["1"]
},
{
"country":"First",
"coupon":["10"]
},
{
"country":"First",
"coupon":["12"]
},
{
"country":"Second",
"coupon":"2"
},
{
"country":"third",
"coupon":"3"
},
{
"country":"fourth",
"coupon":"4"
},
{
"country":"fifth",
"coupon":"5"
}
]
I sorted out the duplicates in JSON and displayed on dropdown
var sortedCountries = [];
if (sortedCountries.indexOf(value.country) == -1) {
$('#sel').append('<option value="' + value.coupon + '">' + value.country + '</option>');
sortedCountries.push(value.country);
}
So when I select each option in the dropdown the corresponding value i.e coupon appears. But I need to generate random values (coupons) when I select the dropdown with "country": "First", How to do that?
回答1:
When I review the link you referenced, I see:
http://www.thegameappstudio.com/watchface/json/thegasfitness.json
This return JSON data like:
[
{
"Application Title": "TheGas Fitness",
"Content ID": "000004891575",
"country": "Spain",
"coupon": "S8ZEUXL19GELB5RN",
"Usable Dates(GMT)": "2020-06-04 00:00",
"Expiration Date(GMT)": "2020-06-30 00:00",
"Remaining Days": 27,
"Coupon Status": "Not Used"
}
]
It uses the following code:
$(document).ready(function() {
$('#sel').select2({
/* Sort data using lowercase comparison */
sorter: data => data.sort((a, b) => a.text.toLowerCase() > b.text.toLowerCase() ? 0 : -1)
});
var url = "http://www.thegameappstudio.com/watchface/json/thegasfitness.json";
$.getJSON(url, function(data) {
var myArray = new Array();
$.each(data, function(index, value) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
$('#sel').append('<option value="' + value.coupon + '">' + value.country + '</option>');
});
});
// SHOW SELECTED VALUE.
$('#sel').change(function() {
var str = $("#sel").val();
$("#txtName").val(str);
});
$("#cpy").click(function(event) {
var copyText = document.getElementById("txtName");
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");
alert("Copied Coupon Code: " + copyText.value);
});
});
So the resulting Select is like:
<select id="sel">
<option value="S8ZEUXL19GELB5RN">Spain</option>
</select>
Your data is vastly different. In your Data, the value is a integer. So in your change
callback, you would need to send that as an Index to your Coupon Array.
$('#sel').change(function() {
var i = $("#sel").val();
$("#txtName").val(coupons[i]);
});
You would need an Array of Coupon codes, containing the Alphanumeric coupons.
来源:https://stackoverflow.com/questions/62284591/how-to-retrieve-random-values-corresponding-to-the-name-in-json