开发者

Encode string javascript so that it can be transmitted to a server

I'm trying to send json string in the get request to the server, here is how it looks before encoding :

filters={"groupOp":"AND","rules":[{"field":"countrycode","op":"eq","data":"ARG"}]}

Naturally I end up with null pointer when trying to get this json string, then I googled this encodeURIComponent and it partially encodes this string like this :

filters={"groupOp"%3A"AND"%2C"rules"%3A[{"field"%3A"countrycode"%2C"op"%3A"eq"%2C"data"%3A"ARG"}]}

But this is how it supposed to be in order to work :

filters=%7B%22groupOp%22%3A%22AND%22%2C%22rules%22%3A%5B%7B%22field%22%3A%22countrycode%22%2C%22op%22%3A%22eq%22%2C%22data%22%3A%22ARG%22%7D%5D%7D

How do I get this, entirely encoded string so I can read it at server side properly ?

Reason why I used get instead of post

I'm sending this filter(json) content to the server side, web service gets data from the database and returns pdf document.

Using post, I'm able to send correct data and the response is successfully displayed in my firebug console. But I need to return pdf doc to override the current page or open new window/tab and return in that开发者_运维技巧 one.


I think you're overworking this problem. Or encoding too many times. Or something. You've got a JSON string, and you are trying to JSON encode it. That seems...unhelpful.

A better approach might be to produce a Javascript object, then JSON.Stringify that, and then transmit it as a parameter.

var thing = {
  groupOp : "AND",
  rules : [
    { field : "countrycode", op : "eq", data : "ARG" },
      ...
  ],
    ...
}; 
var stringrep = JSON.stringify(thing);
// post via jQuery
$.ajax({
  type: 'POST',
  url: url,
  data: stringrep,
  dataType: 'json'
  success: function() { ... },
});

Normally for a JSON stringified message to or from the server, you'd want to use HTTP POST. HTTP GET puts all "parameters" in the URL; there is no message body. In contrast, HTTP POST allows you to attach a message body to the HTTP message, which can be "anything". With that approach, you don't need to url-encode the quotes and spaces; the JSON message just gets transmitted as the message body of the HTTP message.

HTTP POST is the way applications upload images, or transmit XML documents, and so on. Anything complex gets transmitted via POST.


var filtersParameter = 'filters=' + encodeURI(JSON.stringify(filters));


var filtersParameter = 'filters=' + atob(JSON.stringify(filters));

Note: atob() method uses base64 algorithm to encode the data. This encoded data can be easily passed to a server where it can be decoded using corresponding decoding methods (in python base64.b64decode(encoded_string) is used).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜