【问题标题】:Loop through values in jQuery function循环遍历 jQuery 函数中的值
【发布时间】:2017-05-24 10:29:52
【问题描述】:

我尝试了不同的代码和设置,但仍然无法正常工作。我想将数组中的所有值添加到 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 所在的 data 函数循环。但我不知道如何用 myArray 值替换 SPACEKEY 数据?

【问题讨论】:

标签: javascript jquery json ajax rpc


【解决方案1】:

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

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

请参考这个fiddle。 (我已对 AJAX 请求进行了注释,但数据值已正确填写)。

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

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

【讨论】:

  • 谢谢。我已经尝试过了,但是您在 Fiddle 中创建的脚本出现以下错误:“请求正文无法解析为 JSON。”
  • @DannyvandenBerg 我想错误发生在 AJAX 调用中,请记住您已经设置了 contentType: 'application/json',,这意味着无论来自 /rpc/json-rpc/confluenceservice-v2/setSpaceStatus 的响应是什么,都必须是 JSON。我认为该错误来自您要求的“setSpaceStatus”。尝试将 contentType 设置为“text/plain”。
【解决方案2】:

正如您在评论中所说,您希望一次传递一个值,以便发出多个 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);
        }
    }); 
});

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

【讨论】:

  • 谢谢!我猜它几乎可以工作了。但现在我收到以下错误:找不到 RPC 方法:setSpaceStatus 采用 1 个参数
【解决方案3】:

我终于搞定了。感谢您的支持!

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);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    相关资源
    最近更新 更多