Ampersand (&) character inside a value of jQuery AJAX request data option

前端 未结 4 2025
闹比i
闹比i 2020-12-13 09:43

I am performing asynchronous HTTP (Ajax) requests via jQuery with the basic $.ajax(). The code looks like the following:

$(\"textarea\").blur(function(){
            


        
相关标签:
4条回答
  • 2020-12-13 09:53

    Instead of:

    data: "id=" + thisId + "&value=" + thisValue
    

    do:

    data: { id: thisId, value: thisValue }
    

    This way jquery will take care of properly URL encoding the values. String concatenations are the root of all evil :-)

    0 讨论(0)
  • 2020-12-13 09:57

    Strongly recommend you use the solution provided by Darin above if at all possible; that way, you get to reuse well-tested code for building POST data.

    But if you really, really, really need to use string concatenation (here, or elsewhere in your application when building up query strings or POST data out of user inputs), you need to use encodeURIComponent:

    $("textarea").blur(function(){
       var thisId = $(this).attr("id");
       var thisValue = $(this).val();
    
       $.ajax({
          type: "POST",
          url: "some.php",
          data: "id=" + encodeURIComponent(thisId) + "&value=" + encodeURIComponent(thisValue),
          success: function(){
            alert( "Saved successfully!" );
          }
       });
    });
    

    By default when sending a POST with jQuery.ajax, you're sending data with the content type application/x-www-form-urlencoded, which means you're promising that the data is encoded that way. You have to be sure to keep your part of the bargain and actually encode it. This isn't just important for ampersands.

    0 讨论(0)
  • 2020-12-13 09:59
    $.ajax({
    
       type:'POST',
     dataType: "text",
       url:'save.php',
       data:'_id='+$('#id').val()+'&title='+$('#title').val(),
    ??
    data: { id: thisId, value: thisValue }
    
    0 讨论(0)
  • 2020-12-13 10:01

    just use the javascript function encodeURIComponent():

    $("textarea").blur(function(){
       var thisId = $(this).attr("id");
       var thisValue = $(this).val();
    
       $.ajax({
          type: "POST",
          url: "some.php",
          data: "id=" + thisId + "&value=" + encodeURIComponent(thisValue),
          success: function(){
            alert( "Saved successfully!" );
          }
       });
    
    });
    
    0 讨论(0)
提交回复
热议问题