编码网址参数

Encoding URL parameter

本文关键字:参数 编码      更新时间:2023-09-26

我在java脚本端遇到了问题

1)

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

这是我的var文本,我想在服务器端发送它以生成Excel工作表并且浏览器应该提示弹出窗口以保存我正在做的文件

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

问题就像在 var 文本中一样,如果它包含一些特殊字符,如 % 、. 浏览器显示

 The character encoding of the plain text document was not declared

但是没有一个特殊字符对我来说很好。

我有很多谷歌,但想用use window.location.replace(resUri)网址进行编码

任何帮助都会对我有很大帮助。

提前致谢

您需要对

查询字符串的值进行编码,而不是对查询字符串本身进行编码:

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

话虽如此,text很长,因此您应该考虑将其post到新页面,而不是在URL中传递它。使用 jquery 执行此操作的一种方法是创建并提交一个包含所需数据的隐藏表单:

$('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();
});

工作中的 jsfiddle