MandatoryFields = {
User: field,
}
编辑
"api/mapping/mandatoryfield?type=USER" returns
["First Name", "Last Name", "Location", "Email", "Password"],
我的问题是我需要在forEach循环之外访问字段值。如何使用jquery或javascript
编辑
<textarea autocomplete="off" class="form-control rd-control rd-control--textarea empty" cols="20" data-bind="value: offerTitle, expandedTextArea: offerTitle, valueUpdate: 'afterkeydown', customerRequiredFieldsBinding" id="CheckoutWelcomeTitle" name="CheckoutWelcomeTitle" placeholder="ex. Here comes the best offer" rows="1" type="text" data-autosize-on="true" style="overflow-y: hidden; height: 35.9792px;" onblur="setTextColorDefault(this)" oninput="setTextColor(this)">Let's bid on a discount code!</textarea>
查看编辑后的问题,我想在MandatoryFields.User内部使用该字段数组,但是如果我使用它,则不显示值
答案 0 :(得分:1)
这实现了$ .ajax:
GetMandatoryFieldsforUser: function (data) {
var field = [];
$.ajax({
url: "api/mapping/mandatoryfield?type=USER"
}).done(function(data) {
// THIS PORTION IS EXECUTED AFTER DATA IS LOADED
var self = this;
self.dt = [];
self.firmdata = JSON.parse(data.Data);
console.log(self.firmdata);
self.firmdata.forEach(function (item) {
field.push(item.DisplayName);
})
console.log(field)
/*
USE return HERE!
*/
return field; // OR SOMETHING ELSE
})
// THIS WON'T WORK, BECAUSE DATA IS RETRIEVED IN ASYNC!
console.log(field)
},
答案 1 :(得分:0)
您应该在jquery中使用ajax方法。
function GetMandatoryFieldsforUser( data)
{
var field= [];
var scriptUrl = "api/mapping/mandatoryfield?type=USER";
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'html',
async: true,
success: function(data) {
var self = this;
self.dt = [];
self.firmdata = JSON.parse(data.Data);
console.log(self.firmdata);
self.firmdata.forEach(function (item) {
field.push(item.DisplayName);
})
console.log(field)
}
});
return field;
}
答案 2 :(得分:0)
由于$ .get()是异步方法,因此可以使用async / await从$ .get方法的回调中访问返回的值。
GetMandatoryFieldsforUser: async function (data) {
var field = [];
const returnedField = await $.get("api/mapping/mandatoryfield?type=USER", function (data) {
var self = this;
self.dt = [];
self.firmdata = JSON.parse(data.Data);
console.log(self.firmdata);
self.firmdata.forEach(function (item) {
field.push(item.DisplayName);
})
console.log(field) //able to print value
return field;
}).promise()
console.log(returnedField) // not able to print value
},