How to escape “&” ampersand character in form input using jQuery

后端 未结 5 1052
余生分开走
余生分开走 2020-12-30 06:00

I have a problem with my jQuery script that send data via POST method. The problem is whenever it sends data via Ajax that has an "&" ampersand in the sentence

相关标签:
5条回答
  • 2020-12-30 06:27

    You can use a native javascript escape() function

    In line 74

    data: : "&task_d=" + escape(task_d) + "" 
    

    Alternatively, you could enclose your query string values in quotes

    data: : "&task_d='" + task_d + "'" 
    
    0 讨论(0)
  • 2020-12-30 06:28

    If you pass your data parameter as a Javascript object, it will convert the characters for you (and IMO make the code look neater). So you should change your $.ajax call to the following:

    data: {"user_id": user_id, "time_r": time_r, "task_d": task_d, "p_id": p_id, "df": finished},
    
    0 讨论(0)
  • 2020-12-30 06:33

    htmlentites

    This function is identical to htmlspecialchars() in all ways, except with htmlentites(), all characters which have HTML character entity equivalents are translated into these entities.

    If you're wanting to decode instead (the reverse) you can use html_entity_decode().

    Example:

    echo htmlentities("&"); // &
    

    if your directly doing this in the browser you should be able to use:

    encodeURIComponent(string input);
    

    Example:

    encodeURIComponent($.trim($("input[name=t-tim_rendered-"+id+"]").val().toString()));
    
    0 讨论(0)
  • 2020-12-30 06:40

    You could use 'encodeURIComponent' to accomplish the URL encoding for that component. I used this and validated with browsers IE, Firefox, and Chrome.

    0 讨论(0)
  • 2020-12-30 06:49

    I've been having a huge problem exactly with this situation.

    This is just to say that the last answer from Andrew Koester is the perfect answer I was looking for.

    In case you are passing multiple form entries from a jQuery form to PHP through the .ajax() call like this:

    data: "name=" + name + "&message=" + message + ...

    DON'T USE THIS METHOD, it will block the ampersand(&) character from being written by the user on any of the input fields of your form.

    Use this one instead as suggested by Andrew:

    data: {"name": name, "email": email, "subject": subject, "comments": comments},

    This way the user can write any kind of special character whithout worrying a about conflicting with the ajax declaration.

    0 讨论(0)
提交回复
热议问题