最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery param() does not encode parameter properly which have "&" included - Stack Overflo

programmeradmin3浏览0评论

My Application is based on Ajax request/response. I create object of all parameters and make query string using jquery param() method. it works fine but when some parameter contains "&" in it then it does not encode that properly and so server returns error in that case. Can somebody tell me how to create query string in this case when data contains "&" character?

var url = ""
    url += "?username='abc'";
    url += "&" + $.param(params);

/*
   params values are follows:

   params[name] = 'test'
   params[id] = 1234
   params[xyz] = 'entertainment & games'
*/

Also suggest if I have to change something in serverside script to decode this properly

My Application is based on Ajax request/response. I create object of all parameters and make query string using jquery param() method. it works fine but when some parameter contains "&" in it then it does not encode that properly and so server returns error in that case. Can somebody tell me how to create query string in this case when data contains "&" character?

var url = "http://www.abc."
    url += "?username='abc'";
    url += "&" + $.param(params);

/*
   params values are follows:

   params[name] = 'test'
   params[id] = 1234
   params[xyz] = 'entertainment & games'
*/

Also suggest if I have to change something in serverside script to decode this properly

Share Improve this question edited Mar 15, 2011 at 11:14 Bhupi asked Mar 15, 2011 at 10:26 BhupiBhupi 2,9696 gold badges35 silver badges51 bronze badges 1
  • It works for me... I get this: &name=test&id=1234&xyz=entertainment+%26+games. Can you post a plete code snippet? – Álvaro González Commented Mar 15, 2011 at 10:46
Add a ment  | 

2 Answers 2

Reset to default 3

The jQuery.param() method encodes as expected. This snippet...:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3/TR/html4/loose.dtd">
<html>
<head><title></title>
<script type="text/javascript" src="http://ajax.googleapis./ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
jQuery(function($){
    var params = {
        name: "test",
        id: 1234,
        xyz: "entertainment & games"
    };

    var url = ""
    url += "&" + $.param(params);

    alert(url);
});
//--></script>
</head>
<body>


</body>
</html>

... alerts this: &name=test&id=1234&xyz=entertainment+%26+games

You don't say what the error is but it's worth noting that a valid query string should begin with ? rather than &:

var url = ""
url += "?" + $.param(params);

A little consideration:

Probabily that the error was generated by the "'abc'" value for "username" parameter...

url += "?username='abc'";

The correct way should be:

url += "?username=abc";
发布评论

评论列表(0)

  1. 暂无评论