开发者

Passing "&" by POST

I am passing variables to submit file via AJAX but I have problem when I'm passing variable that contains "&" character. I know why, because it's messing the string like id=1&name=blabla&开发者_开发百科;something=q&a.

But how can I make it work?

Someone wanted code, here it is

$("#btnCatEditSubmit").click(function()
            {
                $.ajax(
                {
                    type: "POST",
                    url: "catEditSubmit.php",
                    data: "catID=<?= $catID ?>" + "&catName=<?= $catName ?>",
                    success: function(data)
                    {
                        alert(data);
                    }
                });
            });

catName might be "Something & Something" and then I have problem.


You have to encode / escape them.

In PHP, you can do that with the urlencode() function:

$string = urlencode($string);

So in your code, do that:

data: "catID=<?= urlencode($catID) ?>" + "&catName=<?= urlencode($catName) ?>",

Or even better:

data: <?=json_encode(array('catID' => $catID, 'catName' => $catName))?>,

(jQuery allows you to pass a hash of key-value pairs directly, so jQuery can take care of escaping for you. Here json_encode formats your array in a way understandable by javascript).


In javascript, you can do that with the encodeURIComponent() function:

var escaped_string = encodeURIComponent(str);

But as you are using jQuery, you can also pass variables directly with a hash.

Instead for doing this:

$.ajax({
    data: "a=b&c=d",
    ...
});

Do this:

$.ajax({
    data: {a: "b", c: "d"},
    ...
});

And jQuery will escape everything for you.


You need to escape the "&" character using %26


Use PHP's urlencode() function to make your parameter values URL-safe.


You need to url-encode your &. The code is %26.


You need to escape the & character, as it has a special meaning in URLs. You can do this with the native function encodeURIComponent or, since you are using jQuery, using the $.param helper method:

var querystring = $.param({
    id: 1,
    name: 'blablah',
    something: 'q&a'
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜