如何使用 $.ajax() jquery 发送多个数据 [英] how to send multiple data with $.ajax() jquery

查看:51
本文介绍了如何使用 $.ajax() jquery 发送多个数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 j 查询 $.ajax 方法将多个数据发送到我的 php 脚本,但是当我连接多个数据时我只能传递单个数据我在我的 php 脚本中收到未定义的索引错误 tat 意味着 ajax 请求已发出,但是数据未发送我需要知道我应该如何格式化多个数据以将其连续发送到名称值对中的处理脚本这里是我写的

i am trying to send multiple data using j query $.ajax method to my php script but i can pass only single data when i concatenate multiple data i get undefined index error in my php script tat means the ajax request is made but data is not sent i need to know how should i format multiple data to successively send it to processing script in name vale pair here is what i have written

<script>
  $(document).ready(function() {

    $('#add').click(function () {

      var name = $('#add').attr("data_id");

      var id = $('#add').attr("uid");

      var data = 'id='+ id  & 'name='+ name; // this where i add multiple data using  ' & '

      $.ajax({
        type:"GET",
        cache:false,
        url:"welcome.php",
        data:data,    // multiple data sent using ajax
        success: function (html) {

          $('#add').val('data sent sent');
          $('#msg').html(html);
        }
      });
      return false;
    });
  });
</script>



<span>
  <input type="button" class="gray_button" value="send data" id="add" data_id="1234" uid="4567" />
</span>
<span id="msg"></span>

推荐答案

您可以创建键/值对的对象,jQuery 会为您完成剩下的工作:

You can create an object of key/value pairs and jQuery will do the rest for you:

$.ajax({
    ...
    data : { foo : 'bar', bar : 'foo' },
    ...
});

这样数据就会自动正确编码.如果您确实想编造自己的字符串,请确保使用 encodeURIComponent():https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent

This way the data will be properly encoded automatically. If you do want to concoct you own string then make sure to use encodeURIComponent(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent

您当前的代码无法正常工作,因为字符串未正确编造:

Your current code is not working because the string is not concocted properly:

'id='+ id  & 'name='+ name

应该是:

'id='+ encodeURIComponent(id) + '&name='+ encodeURIComponent(name)

这篇关于如何使用 $.ajax() jquery 发送多个数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆