简体   繁体   中英

Why double encode Jquery Ajax URL

In my JS I use the jQuery ajax function.

Here how it looks like:

$.ajax({
   url: "somepage/" + keyword + "/" + xyz + "/" + abc + "/getbla",
(...)

If the 'keyword' (= value of a textfield) contains a '#' this doesn't work anymore. We all know, that the URL will only be parsed until the # and the rest behind the # will be used eg for an anchor.

So I modified the ajax function to this:

$.ajax({
   url: "somepage/" + encodeURIComponent(keyword) + "/" + xyz + "/" + abc + "/getbla",
(...)

This didn't work either, but in the console I can see the complete url with %23 instead of the #.

Ok this was close to what I was looking for, but the request still doesn't work - I don't know why - thats why I ask here.

I typed %23 in the textfield (=keyword) and the request works perfektly. My php backend is sending back the data I was looking for.

So this is my final solution:

$.ajax({
   url: "somepage/" + encodeURIComponent(encodeURIComponent(keyword)) + "/" + xyz + "/" + abc + "/getbla",
(...)

This is how the PHP-function looks like:

if ($_GET['anyparam'] == 'getbla') {

    $searchString = array(
        'keyword' => trim($_POST['keyword']),
        'xyz' => trim($_POST['xyz']),
        'abc' => trim($_POST['abc'])
    );

    echo json_encode($this->dataBaseFunctions->searchResult($searchString['keyword'], $searchString['xyz'], $searchString['abc']));
  }

Question: Why do I have to double encode the URL?

My guess would be that your using url rewriting, so the initial request goes through and the # is decoded and when redirected everything after the hash is thrown away.
For double encoding the first request will decode to %23 the redirect to #

If you're using mod_rewrite take a look at https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_b

我认为这条规则正是我所寻求的:

RewriteRule ^somepage/([^/]+)/([0-9]+)/?$ somepage&param1=${unesc:$1}&param2=$2 [L]

根据这个你不使用encodeURIComponent输入的url实际上很好,你只是编码正确的url,这使得它不正确,所以你必须应用2次才能使它从correct-> not correct-> correct。

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