代码之家  ›  专栏  ›  技术社区  ›  Nik Sumeiko

jquery ajax请求数据选项的值内的和号(&)字符

  •  29
  • Nik Sumeiko  · 技术社区  · 14 年前

    我正在通过jquery和basic$.ajax()执行异步HTTP(Ajax)请求。代码如下:

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

    一切正常,直到用户输入 特克斯塔利亚 和号(&)字符。 而当我调试保存值的PHP函数时,它总是有一个值,直到这个字符。

    我认为必须有一个解决方案,以某种方式跳过和号(&)。有什么想法吗?

    4 回复  |  直到 14 年前
        1
  •  83
  •   Darin Dimitrov    14 年前

    而不是:

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

    做:

    data: { id: thisId, value: thisValue }
    

    这样jquery将负责正确地对值进行URL编码。字符串连接是万恶之源:-)

        2
  •  26
  •   Community CDub    8 年前

    强烈建议您使用 solution provided by Darin 以上,如果可能的话;这样,您就可以重用经过良好测试的代码来构建 POST 数据。

    但是,如果您真的,真的,真的需要使用字符串连接(在这里,或者在构建查询字符串或 数据超出用户输入),您需要使用 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!" );
          }
       });
    });
    

    发送时默认 具有 jQuery.ajax ,您正在发送内容类型的数据 application/x-www-form-urlencoded ,这意味着您保证数据是以这种方式编码的。你必须确保保留你的部分,并实际编码。这不仅对符号符号很重要。

        3
  •  6
  •   js1568    14 年前

    只需使用javascript函数 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!" );
          }
       });
    
    });
    
        4
  •  0
  •   Rahil Wazir Joseph Daigle    11 年前
    $.ajax({
    
       type:'POST',
     dataType: "text",
       url:'save.php',
       data:'_id='+$('#id').val()+'&title='+$('#title').val(),
    ??
    data: { id: thisId, value: thisValue }