JavaScript 数组到 URL 编码

发布于 2024-10-11 09:07:11 字数 626 浏览 3 评论 0原文

有没有js函数可以将数组转换为urlencoded? 我完全是 JS 新手...谢谢!...


我的数组是一个关键 &值数组.... 那么,

myData=new Array('id'=>'354313','fname'=>'Henry','lname'=>'Ford');

是一样的,

myData['id']='354313';
myData['fname']='Henry';
myData['lname']='Ford';
myData.join('&'); //returns error, it doesn't work on such array...

有什么解决办法吗?


哦,对不起…… 我有一个这样的数组

var myData=new Array('id'=>'354313','fname'=>'Henry','lname'=>'Ford');

,那么我需要将数组转换为:

id=354313&fname=Henry&lname=Ford

is there any js function to convert an array to urlencoded?
i'm totally newbie n JS... thanks!...


my array is a key & value array....
so,

myData=new Array('id'=>'354313','fname'=>'Henry','lname'=>'Ford');

is the same as

myData['id']='354313';
myData['fname']='Henry';
myData['lname']='Ford';
myData.join('&'); //returns error, it doesn't work on such array...

is there any solution?


oh sory...
i have an array like this

var myData=new Array('id'=>'354313','fname'=>'Henry','lname'=>'Ford');

then i need the array converted to be:

id=354313&fname=Henry&lname=Ford

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

千秋岁 2024-10-18 09:07:11

试试这个:

var myData = {'id': '354313', 'fname':'Henry', 'lname': 'Ford'};
var out = [];

for (var key in myData) {
    if (myData.hasOwnProperty(key)) {
        out.push(key + '=' + encodeURIComponent(myData[key]));
    }
}

out.join('&');

有关为什么使用 hasOwnProperty 的解释,请查看这个“我如何循环”的答案通过或枚举 JavaScript 对象?”

Try this:

var myData = {'id': '354313', 'fname':'Henry', 'lname': 'Ford'};
var out = [];

for (var key in myData) {
    if (myData.hasOwnProperty(key)) {
        out.push(key + '=' + encodeURIComponent(myData[key]));
    }
}

out.join('&');

For an explanation about why use hasOwnProperty, take a look at this answer to "How do I loop through or enumerate a JavaScript object?".

唱一曲作罢 2024-10-18 09:07:11

如果您使用 jQuery,可以使用 $.param()。检查此处
的示例

var myData = {'id' : '354313', 'fname' : 'Henry', 'lname' : 'Ford'};
var url = "https://stackoverflow.com?" + $.param(myData);

使用Output

https://stackoverflow.com?id=354313&fname=Henry&lname=Ford

也适用于对象数组(例如来自 jQuery(form).serializeArray()):

var myData = [{'id' : '354313'}, {'fname' : 'Henry'},{'lname' : 'Ford'}];

If you use jQuery, can use $.param(). Check here .
Example of using

var myData = {'id' : '354313', 'fname' : 'Henry', 'lname' : 'Ford'};
var url = "https://stackoverflow.com?" + $.param(myData);

Output is

https://stackoverflow.com?id=354313&fname=Henry&lname=Ford

Also works with an array of objects (like from jQuery(form).serializeArray()) :

var myData = [{'id' : '354313'}, {'fname' : 'Henry'},{'lname' : 'Ford'}];
野の 2024-10-18 09:07:11

你可以这样做:

var myData = new Array('id=354313', 'fname=Henry', 'lname=Ford');
var url = myData.join('&');

You can do something like this:

var myData = new Array('id=354313', 'fname=Henry', 'lname=Ford');
var url = myData.join('&');
逐鹿 2024-10-18 09:07:11

如果你使用对象而不是数组,你可以这样做(ES6):

var myData = {
    id: 354313,
    fname: 'Henry',
    lname: 'Ford',
    url: 'https://es.wikipedia.org/wiki/Henry_Ford',
};

encodeDataToURL = (data) => {
    return Object
      .keys(data)
      .map(value => `${value}=${encodeURIComponent(data[value])}`)
      .join('&');
 }

console.log(encodeDataToURL(myData));

If you use an object instead of an array you can do this (ES6) :

var myData = {
    id: 354313,
    fname: 'Henry',
    lname: 'Ford',
    url: 'https://es.wikipedia.org/wiki/Henry_Ford',
};

encodeDataToURL = (data) => {
    return Object
      .keys(data)
      .map(value => `${value}=${encodeURIComponent(data[value])}`)
      .join('&');
 }

console.log(encodeDataToURL(myData));
紧拥背影 2024-10-18 09:07:11

迟到了,但我所做的这个解决方案可以处理递归性和嵌套数组/对象

function is(className, object) {
    return Object.prototype.toString.call(object) === '[object '+ className +']';
}

const DataEncoder = function() {
    this.levels = [];
}

DataEncoder.prototype.__dataEncoding = function(data, actualKey = null) {
    let finalString = '';
    if (actualKey) {
        this.levels.push(actualKey);
    }

    const keys = Object.keys(data);
    const l = keys.length;
    for(let a = 0; a < l; a++) {
        const key = keys[a];
        let value = data[key];

        if (is('Object', value)) {
            finalString += this.__dataEncoding(value, key);
        } else if (is('Array', value)) {
            const arrValSize = value.length;
            for (let b = 0; b < arrValSize; b++) {
                let arrVal = value[b];
                if (actualKey) {
                    finalString += actualKey;
                    for(let c = 1; c < this.levels.length; c++) finalString += '[' + this.levels[c] + ']';
                    if (arrVal === undefined || arrVal === null) arrVal = '';
                    finalString += '[' + key + '][]=' + arrVal + '&';
                } else {
                    if (arrVal === undefined || arrVal === null) arrVal = '';
                    finalString += key + '[]=' + arrVal + '&';
                }
            }
        } else {
            if (actualKey) {
                finalString += this.levels[0];
                for(let c = 1; c < this.levels.length; c++) finalString += '[' + this.levels[c] + ']';
                if (value === undefined || value === null) value = '';
                finalString += '[' + key + ']=' + value + '&';
            } else {
                if (value === undefined || value === null) value = '';
                finalString += key + '=' + value + '&';
            }
        }
    }
    this.levels.pop();
    return finalString;
}

DataEncoder.prototype.encode = function(data) {
    if (!is('Object', data) || data === {}) return null;
    return this.__dataEncoding(data).slice(0, -1);
}

用法:

const testData = {
  name: "John",
  age: 13,
  skills: ['games', 'programming', 'reading', 'singing'],
  invests: {
    education: [120.3, 50.5],
    kids: 70,
    optical: {
      north: 20.5,
      south: 10.70,
      west: 6,
      east: [7]
    },
    deeper: {
      first: {
        landing: 5
      }
    }
  }
};
const encoder = new DataEncoder();
encoder.encode(testData);

结果:

name=John&age=13&skills[]=games&skills[]=programming&skills[]=reading&skills[]=singing&invests[education][]=120.3&invests[education][]=50.5&invests[kids]=70&invests[optical][north]=20.5&invests[optical][south]=10.7&invests[optical][west]=6&optical[optical][east][]=7&invests[deeper][first][landing]=5

我知道它需要encodeURIComponent方法,但可以轻松添加


编辑,改进

function is(className, object) {
    return Object.prototype.toString.call(object) === '[object '+ className +']';
}

const DataEncoder = function() {
    this.levels = [];
    this.actualKey = null;

}

DataEncoder.prototype.__dataEncoding = function(data) {
    let uriPart = '';
    const levelsSize = this.levels.length;
    if (levelsSize) {
      uriPart = this.levels[0];
      for(let c = 1; c < levelsSize; c++) {
        uriPart += '[' + this.levels[c] + ']';
      }
    }
    let finalString = '';
    if (is('Object', data)) {
        const keys = Object.keys(data);
        const l = keys.length;
        for(let a = 0; a < l; a++) {
            const key = keys[a];
            let value = data[key];
            this.actualKey = key;
            this.levels.push(this.actualKey);
            finalString += this.__dataEncoding(value);
        }
    } else if (is('Array', data)) {
        if (!this.actualKey) throw new Error("Directly passed array does not work")
        const aSize = data.length;
        for (let b = 0; b < aSize; b++) {
            let aVal = data[b];
            this.levels.push(b);
            finalString += this.__dataEncoding(aVal);
        }
    } else {
        finalString += uriPart + '=' + encodeURIComponent(data) + '&';
    }
    this.levels.pop();
    return finalString;
}

DataEncoder.prototype.encode = function(data) {
    if (!is('Object', data) || !Object.keys(data).length) return null;
    return this.__dataEncoding(data).slice(0, -1);
}

现在它可以处理任何深度的嵌套数组/objects,此编辑具有相同的用法

const testData = {
  name: "John",
  age: 13,
  skills: ['games', 'programming', 'reading', 'singing'],
  invests: {
    education: [120.3, 50.5],
    kids: 70,
    optical: {
      north: 20.5,
      south: 10.70,
      west: 6,
      east: [7]
    },
    deeper: {
      first: {
        landing: 5,
        arrayLike: [
          {
            despite: true,
            superb: 'yes',
            omg: {
              kiss: ['la'],
              maybe: {
                thiss: {
                  wont: {
                    work: 'false'
                  }
                }
              }
            },
            incredible: ['lalolanda', 'raidcall', 'phase', [5], [{waw: '@wesome'}]],
          }
        ]
      }
    }
  }
};
const encoder = new DataEncoder();
encoder.encode(testData);

结果:

name=John&age=13&skills[0]=games&skills[1]=programming&skills[2]=reading&skills[3]=singing&invests[education][0]=120.3&invests[education][1]=50.5&invests[kids]=70&invests[optical][north]=20.5&invests[optical][south]=10.7&invests[optical][west]=6&invests[optical][east][0]=7&invests[deeper][first][landing]=5&invests[deeper][first][arrayLike][0][despite]=true&invests[deeper][first][arrayLike][0][superb]=yes&invests[deeper][first][arrayLike][0][omg][kiss][0]=la&invests[deeper][first][arrayLike][0][omg][maybe][thiss][wont][work]=false&invests[deeper][first][arrayLike][0][incredible][0]=lalolanda&invests[deeper][first][arrayLike][0][incredible][1]=raidcall&invests[deeper][first][arrayLike][0][incredible][2]=phase&invests[deeper][first][arrayLike][0][incredible][3][0]=5&invests[deeper][first][arrayLike][0][incredible][4][0][waw]=%40wesome

Late to the party, but this solution I have made can handle recursivity, and nested array/object

function is(className, object) {
    return Object.prototype.toString.call(object) === '[object '+ className +']';
}

const DataEncoder = function() {
    this.levels = [];
}

DataEncoder.prototype.__dataEncoding = function(data, actualKey = null) {
    let finalString = '';
    if (actualKey) {
        this.levels.push(actualKey);
    }

    const keys = Object.keys(data);
    const l = keys.length;
    for(let a = 0; a < l; a++) {
        const key = keys[a];
        let value = data[key];

        if (is('Object', value)) {
            finalString += this.__dataEncoding(value, key);
        } else if (is('Array', value)) {
            const arrValSize = value.length;
            for (let b = 0; b < arrValSize; b++) {
                let arrVal = value[b];
                if (actualKey) {
                    finalString += actualKey;
                    for(let c = 1; c < this.levels.length; c++) finalString += '[' + this.levels[c] + ']';
                    if (arrVal === undefined || arrVal === null) arrVal = '';
                    finalString += '[' + key + '][]=' + arrVal + '&';
                } else {
                    if (arrVal === undefined || arrVal === null) arrVal = '';
                    finalString += key + '[]=' + arrVal + '&';
                }
            }
        } else {
            if (actualKey) {
                finalString += this.levels[0];
                for(let c = 1; c < this.levels.length; c++) finalString += '[' + this.levels[c] + ']';
                if (value === undefined || value === null) value = '';
                finalString += '[' + key + ']=' + value + '&';
            } else {
                if (value === undefined || value === null) value = '';
                finalString += key + '=' + value + '&';
            }
        }
    }
    this.levels.pop();
    return finalString;
}

DataEncoder.prototype.encode = function(data) {
    if (!is('Object', data) || data === {}) return null;
    return this.__dataEncoding(data).slice(0, -1);
}

Usage:

const testData = {
  name: "John",
  age: 13,
  skills: ['games', 'programming', 'reading', 'singing'],
  invests: {
    education: [120.3, 50.5],
    kids: 70,
    optical: {
      north: 20.5,
      south: 10.70,
      west: 6,
      east: [7]
    },
    deeper: {
      first: {
        landing: 5
      }
    }
  }
};
const encoder = new DataEncoder();
encoder.encode(testData);

Result:

name=John&age=13&skills[]=games&skills[]=programming&skills[]=reading&skills[]=singing&invests[education][]=120.3&invests[education][]=50.5&invests[kids]=70&invests[optical][north]=20.5&invests[optical][south]=10.7&invests[optical][west]=6&optical[optical][east][]=7&invests[deeper][first][landing]=5

I know that it needs encodeURIComponent method, but can be added easily


EDIT, IMPROVEMENTS

function is(className, object) {
    return Object.prototype.toString.call(object) === '[object '+ className +']';
}

const DataEncoder = function() {
    this.levels = [];
    this.actualKey = null;

}

DataEncoder.prototype.__dataEncoding = function(data) {
    let uriPart = '';
    const levelsSize = this.levels.length;
    if (levelsSize) {
      uriPart = this.levels[0];
      for(let c = 1; c < levelsSize; c++) {
        uriPart += '[' + this.levels[c] + ']';
      }
    }
    let finalString = '';
    if (is('Object', data)) {
        const keys = Object.keys(data);
        const l = keys.length;
        for(let a = 0; a < l; a++) {
            const key = keys[a];
            let value = data[key];
            this.actualKey = key;
            this.levels.push(this.actualKey);
            finalString += this.__dataEncoding(value);
        }
    } else if (is('Array', data)) {
        if (!this.actualKey) throw new Error("Directly passed array does not work")
        const aSize = data.length;
        for (let b = 0; b < aSize; b++) {
            let aVal = data[b];
            this.levels.push(b);
            finalString += this.__dataEncoding(aVal);
        }
    } else {
        finalString += uriPart + '=' + encodeURIComponent(data) + '&';
    }
    this.levels.pop();
    return finalString;
}

DataEncoder.prototype.encode = function(data) {
    if (!is('Object', data) || !Object.keys(data).length) return null;
    return this.__dataEncoding(data).slice(0, -1);
}

Now it can handle any deep, with nested array/objects, this edit has the same usage

const testData = {
  name: "John",
  age: 13,
  skills: ['games', 'programming', 'reading', 'singing'],
  invests: {
    education: [120.3, 50.5],
    kids: 70,
    optical: {
      north: 20.5,
      south: 10.70,
      west: 6,
      east: [7]
    },
    deeper: {
      first: {
        landing: 5,
        arrayLike: [
          {
            despite: true,
            superb: 'yes',
            omg: {
              kiss: ['la'],
              maybe: {
                thiss: {
                  wont: {
                    work: 'false'
                  }
                }
              }
            },
            incredible: ['lalolanda', 'raidcall', 'phase', [5], [{waw: '@wesome'}]],
          }
        ]
      }
    }
  }
};
const encoder = new DataEncoder();
encoder.encode(testData);

Result:

name=John&age=13&skills[0]=games&skills[1]=programming&skills[2]=reading&skills[3]=singing&invests[education][0]=120.3&invests[education][1]=50.5&invests[kids]=70&invests[optical][north]=20.5&invests[optical][south]=10.7&invests[optical][west]=6&invests[optical][east][0]=7&invests[deeper][first][landing]=5&invests[deeper][first][arrayLike][0][despite]=true&invests[deeper][first][arrayLike][0][superb]=yes&invests[deeper][first][arrayLike][0][omg][kiss][0]=la&invests[deeper][first][arrayLike][0][omg][maybe][thiss][wont][work]=false&invests[deeper][first][arrayLike][0][incredible][0]=lalolanda&invests[deeper][first][arrayLike][0][incredible][1]=raidcall&invests[deeper][first][arrayLike][0][incredible][2]=phase&invests[deeper][first][arrayLike][0][incredible][3][0]=5&invests[deeper][first][arrayLike][0][incredible][4][0][waw]=%40wesome
最冷一天 2024-10-18 09:07:11
var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [ 1, 2, 3 ]
};
var recursiveEncoded = $.param( myObject );
var recursiveDecoded = decodeURIComponent( $.param( myObject ) );

alert( recursiveEncoded );
alert( recursiveDecoded );

recursiveEncoded 和 recursiveDecoded 的值警报如下:

a%5Bone%5D=1&a%5Btwo%5D=2&a%5B Three%5D=3&b%5B%5D=1&b%5B%5D=2& ;b%5B%5D=3
a[一]=1&a[二]=2&a[三]=3&b[]=1&b[]=2&b[]=3

https://api.jquery.com/jQuery.param/

var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [ 1, 2, 3 ]
};
var recursiveEncoded = $.param( myObject );
var recursiveDecoded = decodeURIComponent( $.param( myObject ) );

alert( recursiveEncoded );
alert( recursiveDecoded );

The values of recursiveEncoded and recursiveDecoded are alerted as follows:

a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3
a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3

https://api.jquery.com/jQuery.param/

多彩岁月 2024-10-18 09:07:11

取自 jgrunds 答案,如果你想扩展数组功能

Array.prototype.toQueryString = function(){
    var out = new Array();

    for(key in this){
        out.push(key + '=' + encodeURIComponent(this[key]));
    }

    return out.join('&');
}

或者如果你想要一个独立的函数

function arrayToQueryString(array_in){
    var out = new Array();

    for(var key in array_in){
        out.push(key + '=' + encodeURIComponent(array_in[key]));
    }

    return out.join('&');
}

Taken from jgrunds answer, if you want to extend the array functionality

Array.prototype.toQueryString = function(){
    var out = new Array();

    for(key in this){
        out.push(key + '=' + encodeURIComponent(this[key]));
    }

    return out.join('&');
}

Or if you want a standalone function

function arrayToQueryString(array_in){
    var out = new Array();

    for(var key in array_in){
        out.push(key + '=' + encodeURIComponent(array_in[key]));
    }

    return out.join('&');
}
倾`听者〃 2024-10-18 09:07:11

查看函数 escape 和 unescape

Look at the function escape and unescape.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文