简体   繁体   中英

Encoding URL parameter

I am stuck with the problem at java script side

1)

var text='{"type": "comTocomp","data":[{ "1" : "Key Parameters" , "2" : "Steel - Sponge/ Pig Iron"},   
          { "1" : "No of Companies" , "2" : "6,6 %  "  }]}';

This is my var text i want to send it server side for generating the excel sheet and also the browser should prompt with popup as to save the file for this i am doing

2)

       var url="/XXX/YYYY/genrateSheet";       // URL OF CONTROLLER
       var encode=url+ "?data="+text;          // URL + PARAMETER+ TEXT CONTENT 
        var resUri=encodeURIComponent(encode); // TRIED TO ENCODE BUT DOESN'T WORK
        **window.location.replace(resUri);**       // CALLING TO CONTROLLER TO PROMPT POPUP

The problem is as in var text if it content some special character like % , . the browser shows

 The character encoding of the plain text document was not declared

But none of the special character then works fine for me.

I have Google a lot but want to encode the url with the use window.location.replace(resUri)

any help would be help me a lot.

Thanks in Advance

You need to encode the value of the querystring not the querystring itself:

var url="/XXX/YYYY/genrateSheet";       // URL OF CONTROLLER
var resUri = url + "?data=" + encodeURIComponent(text); // querystring
window.location.replace(resUri);

Saying that, text is quite long, so you should consider post ing it to the new page, instead of passing it in the URL. One way to do that using jquery is to create and submit a hidden form containing the data you want:

$('button').on('click', function() {

    var text='{"type": "comTocomp","data":[{ "1" : "Key Parameters" , "2" : "Steel - Sponge/ Pig Iron"}, { "1" : "No of Companies" , "2" : "6,6 %  "  }]}';

    // create a hidden form    
    var theForm = $('<form action="/XXX/YYYY/genrateSheet" method="post"/>').hide();

    // create a textarea named data and set your json inside it
    var theTextarea = $('<textarea name="data"/>').val(text); // data in your case

    // add the textarea to the form
    theForm.append(theTextarea);

    // submit the form
    theForm.submit();
});

Working jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM