将JavaScript对象转换为URI编码的字符串 [英] Convert JavaScript object into URI-encoded string

查看:105
本文介绍了将JavaScript对象转换为URI编码的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript对象,希望获得 x-www-form-urlencoded

I got a JavaScript object which I would like to get x-www-form-urlencoded.

类似于 $('#myform')。serialize()的东西,但是对于对象。

Something like $('#myform').serialize() but for objects.

以下对象:

{
    firstName: "Jonas",
    lastName: "Gauffin"
}

将被编码为:

firstName = Jonas& lastName = Gauffin (请注意特殊字符应正确编码)

firstName=Jonas&lastName=Gauffin (do note that special characters should get encoded properly)

推荐答案

请仔细查看我在此处提供的两个答案,以确定最适合您的情况。

Please look closely at both answers I provide here to determine which fits you best.

您需要的内容:准备将JSON作为单个参数在URL中使用,以供以后解码。

Likely what you need: Readies a JSON to be used in a URL as a single argument, for later decoding.

jsfiddle

jsfiddle

encodeURIComponent(JSON.stringify({"test1":"val1","test2":"val2"}))+"<div>");

结果:

%7B%22test%22%3A%22val1%22%2C%22test2%22%3A%22val2%22%7D

对于那些只想使用函数的人:

For those who just want a function to do it:

function jsonToURI(json){ return encodeURIComponent(JSON.stringify(json)); }

function uriToJSON(urijson){ return JSON.parse(decodeURIComponent(urijson)); }






答案2:



使用JSON作为 x-www-form-urlencoded 输出的键值对的来源。


Answer 2:

Uses a JSON as a source of key value pairs for x-www-form-urlencoded output.

jsfiddle

jsfiddle

// This should probably only be used if all JSON elements are strings
function xwwwfurlenc(srcjson){
    if(typeof srcjson !== "object")
      if(typeof console !== "undefined"){
        console.log("\"srcjson\" is not a JSON object");
        return null;
      }
    u = encodeURIComponent;
    var urljson = "";
    var keys = Object.keys(srcjson);
    for(var i=0; i <keys.length; i++){
        urljson += u(keys[i]) + "=" + u(srcjson[keys[i]]);
        if(i < (keys.length-1))urljson+="&";
    }
    return urljson;
}

// Will only decode as strings
// Without embedding extra information, there is no clean way to
// know what type of variable it was.
function dexwwwfurlenc(urljson){
    var dstjson = {};
    var ret;
    var reg = /(?:^|&)(\w+)=(\w+)/g;
    while((ret = reg.exec(urljson)) !== null){
        dstjson[ret[1]] = ret[2];
    }
    return dstjson;
}

这篇关于将JavaScript对象转换为URI编码的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆