我希望有人可以帮助我,我有一个jquery函数,它从php表单获取值,我需要为ajax调用创建变量。是否可以在var
中添加循环这是我的代码,所以希望能更好地解释我想要做的事情
...
var teacher_ids = $( '#teacher_ids' ).val();
var status = 'pending';
var array = teacher_ids.split(',');
var data = {
name: title,
short_description: excerpt,
description: content,
status: status,
type: 'variable',
variations : [
这就是我遇到问题的地方,我有多个值,我希望能够循环使用
$.each(array,function (i, item) {
variation_type = item.split('_');
{
regular_price: half_hour,
attributes: [{
id:3,
slug: 'pa_lessonduration',
//name: 'lessonduration',
option: '1-hour'
},{
id: 1,
slug: 'pa_weekday',
// name: 'weekday',
option: variation_type[0]
},{
id: 2,
slug: 'pa_daytime',
//name: 'daytime',
option: variation_type[1],
}]
//"expected an assignment or function call and instead saw an expression?"
}
//"expected ( saw { "
})
$.ajax({
method: "PUT",
url: POST_SUBMITTER.root + 'wc/v1/products/'+ product_id +'',
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', POST_SUBMITTER.nonce );
},
success : function( response ) {
console.log( response );
alert( POST_SUBMITTER.success );
},
fail : function( response ) {
console.log( response );
alert( POST_SUBMITTER.failure );
}
});
有关如何让这个工作的任何建议,请。这应该打印以下但我得到错误
var data = {
name: title,
short_description: excerpt,
description: content,
status: status,
type: 'variable',
variations: [{
regular_price: '19.99',
attributes: [{
id: 3,
name: 'pa_lessonduration',
option: '1-hour'
}, {
name: 'pa_daytime',
option: '0900'
}, {
name: 'weekday',
option: 'monday'
}]
},
{
regular_price: '19.99',
attributes: [{
id: 3,
name: 'pa_lessonduration',
option: '1-hour'
}, {
name: 'pa_daytime',
option: '1100'
}, {
name: 'weekday',
option: 'wednesday'
}]
}]
}
等等......
我希望这是有道理的,如果不问,我会尽力使其更清晰
答案 0 :(得分:0)
下面的代码定义了稍后在variation
中使用的数组data
。
var teacher_ids = $( '#teacher_ids' ).val();
var status = 'pending';
var array = teacher_ids.split(',');
variation=[]; // Declare an empty array
// Then define it
for(i=0;i<array.length;i++){
variation_type = array[i].split('_');
variation[i] = {
regular_price: half_hour,
attributes: [{
id:3,
slug: 'pa_lessonduration',
//name: 'lessonduration',
option: '1-hour'
},{
id: 1,
slug: 'pa_weekday',
// name: 'weekday',
option: variation_type[0]
},{
id: 2,
slug: 'pa_daytime',
//name: 'daytime',
option: variation_type[1]
}]
}
}
var data = { // Define data
name: title,
short_description: excerpt,
description: content,
status: status,
type: 'variable',
variations : variation // This is the array defined in the loop above
}
$.ajax({
method: "PUT",
url: POST_SUBMITTER.root + 'wc/v1/products/'+ product_id +'',
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', POST_SUBMITTER.nonce );
},
success : function( response ) {
console.log( response );
alert( POST_SUBMITTER.success );
},
fail : function( response ) {
console.log( response );
alert( POST_SUBMITTER.failure );
}
});