dqvzfp6468 2018-09-10 23:10
浏览 60

使用Javascript将URL查询字符串传递到HTML表单字段

I have always used PHP for passing query strings into forms, but I am looking to move to a static site scenario and need the query data from a URL to populate the form fields.

I have the code with no console errors, but the data is not passing into the form fields. Does anyone know how this can be done that works across all modern and legacy browsers?

function getQueryString() {
    var result = {};
    if(!window.location.search.length) return result;
    var qs = window.location.search.slice(1);
    var parts = qs.split("&");
    for(var i=0, len=parts.length; i<len; i++) {
        var tokens = parts[i].split("=");
        result[tokens[0]] = decodeURIComponent(tokens[1]);
    }
    return result;
}

$(document).ready(function() {
    $("#theForm").submit(function(e) {
        //var that = this;
        var qs = getQueryString();
        for(var key in qs) {
            var field = $(document.createElement("input"));
            field.attr("name", key).attr("type","hidden");
            field.val(qs[key]);
            $(this).append(field);
        }
    });
});

https://formpopulate.netlify.com/index.html?name=john&email=john@aol.com https://formpopulate.netlify.com/

  • 写回答

1条回答 默认 最新

  • du9843 2018-09-10 23:35
    关注

    You should use URL seachParams:

    var params = (new URL("https://example.com/?name=Jonathan&age=18&test=a%20long%20string")).searchParams;
    var name = params.get("name"); console.log(name); // is the string "Jonathan"
    var age = parseInt(params.get("age")); console.log(age);// is the number 18
    var test = params.get("test"); console.log(test); // is a long string

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)