在jQuery函数

时间:2017-05-24 10:29:52

标签: javascript jquery json ajax rpc

我尝试过不同的代码和设置,但我仍然没有尝试它应该如何。我想将数组中的所有值添加到jQuery的makeSpaceInactive函数中。

$(document).ready(function() {

var myArray = [ 'AB', 'AC']

function makeSpaceInactive(spaceKey) {
    jQuery.ajax({
        contentType: 'application/json',
        type: 'POST',
        url: '/rpc/json-rpc/confluenceservice-v2/setSpaceStatus',
        data: '["SPACEKEY", "ARCHIVED"]',
        success: function(response) {
          console.log(response);
        }, error: function(response) {
          console.log(response);
        }
    }); 
});

$.each(myArray, function (index, value) {
    makeSpaceInactive(value);
});

})

myArray中的值应该在makeSpaceInactive函数中使用SPACEKEY所在的数据函数循环。但我不知道如何用myArray值替换SPACEKEY数据?

3 个答案:

答案 0 :(得分:0)

嗯,你有一些sintax错误,比如最后一次}),但这不是我从你的问题中理解的。据我所知,你的问题是知道如何将POST参数传递给AJAX请求。

只需将['SPACEKEY','ARCHIVED']替换为{arrayelement:spaceKey},如果您希望传递更多元素,请用逗号分隔它们。 例如。 {arrayoneelement:spaceKey1,arraytwoelement:spaceKey2}

请参阅此fiddle。 (我已经注释了AJAX请求,但正确填充了数据值。)

希望这会对你有所帮助。如果您需要更多建议请告诉我。

编辑:小提琴链接错误,已更正,抱歉。

答案 1 :(得分:0)

正如您在评论中所说,您希望一次传递一个值,以便进行多次AJAX请求。问题是“AJAX”中的“A”代表“异步”。因此,您无法确保程序在发送新请求之前等待响应。

您可能想要更改解决方案,我认为为阵列中的每个元素发出几个AJAX请求并不是一个好主意。尝试将数组作为数据发送,并使服务器端程序解释它。类似的东西:

function makeSpaceInactive(myArray) {
    jQuery.ajax({
        contentType: 'application/json',
        type: 'POST',
        url: '/rpc/json-rpc/confluenceservice-v2/setSpaceStatus',
        data: {arrayData:myArray,status:'ARCHIVED'},
        success: function(response) {
          console.log(response);
        }, error: function(response) {
          console.log(response);
        }
    }); 
});

让你的服务端脚本循环数组并返回一个适当的响应。希望它有所帮助。

答案 2 :(得分:0)

我终于有了工作。感谢您的支持!

var myArray ['spaceKey', 'spaceKey'];

function makeSpaceInactive(value) {
    jQuery.ajax({
        contentType: 'application/json',
        type: 'POST',
        url: '/rpc/json-rpc/confluenceservice-v2/setSpaceStatus',
        data: JSON.stringify([value, "ARCHIVED"]),
        success: function(response) {
          console.log(response);
        }, error: function(response) {
          console.log(response);
        }
    });
};

$.each(myArray, function (index, value) {
  makeSpaceInactive(value);
});
相关问题