Convert URL to json

前端 未结 6 1269
太阳男子
太阳男子 2020-12-09 04:55

I can\'t seem to find an answer to this question.. How can I convert a URL parameters string to JSON in javascript? I mean to ask if there is an in-built function like this

6条回答
  •  一整个雨季
    2020-12-09 05:11

    I used satpal's answer to provide a nice Razor to JSON pipeline that works with Html.BeginForm, @Html.TextBoxFor etc.

    The updated getUrlVars function looks like this:

    function getUrlVars(url) {
        var hash;
        var myJson = {};
        var hashes = url.slice(url.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            var value = decodeURIComponent(hash[1]);
            value = value.replace("[\"", "");
            value = value.replace("\"]", "");
            value = value.replace(/\^.*/, "");
            myJson[hash[0]] = value;
        }
        return myJson;
    }
    

    The extra replace calls are for characters I get in my text boxes, probably via the dropdown magicSuggest lookups. The decodeURIComponent call cleans it up from %'s first.

    I call it in a block like this:

        var serialized = $("#saveForm").serialize();
        var params = getUrlVars(serialized);
    

    The Razor syntax I have looks like this:

    @using (Html.BeginForm("SaveNewAddress", "Internal", FormMethod.Post, new { @Id = "saveForm" }))
    {
        @Html.ValidationSummary()
    
        
    Yes
    ...etc

    This provides a nice way to get a bunch of data created in and via ASP.Net MVC controls in a js object that I can throw at a webservice via ajax.

    提交回复
    热议问题