how to send multiple data with $.ajax() jquery

2019-01-05 00:00发布

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 ajax
9条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-05 00:29
var data = 'id='+ id  & 'name='+ name;

The ampersand needs to be quoted as well:

var data = 'id='+ id  + '&name='+ name;
查看更多
疯言疯语
3楼-- · 2019-01-05 00:33

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

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

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

should be:

'id='+ encodeURIComponent(id) + '&name='+ encodeURIComponent(name)
查看更多
Ridiculous、
4楼-- · 2019-01-05 00:37
var value1=$("id1").val();
var value2=$("id2").val();
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
查看更多
Juvenile、少年°
5楼-- · 2019-01-05 00:37

I would recommend using a hash instead of a param string:

data = {id: id, name: name}
查看更多
Summer. ? 凉城
6楼-- · 2019-01-05 00:38

you can use FormData

take look at my snippet from MVC

var fd = new FormData();
fd.append("ProfilePicture", $("#mydropzone")[0].files[0]);// getting value from form feleds 
d.append("id", @(((User) Session["User"]).ID));// getting value from session

$.ajax({
    url: '@Url.Action("ChangeUserPicture", "User")',
    dataType: "json",
    data: fd,//here is your data
    processData: false,
    contentType: false,
    type: 'post',
    success: function(data) {},
查看更多
劫难
7楼-- · 2019-01-05 00:44
var CommentData= "u_id=" + $(this).attr("u_id") + "&post_id=" + $(this).attr("p_id") + "&comment=" + $(this).val();
查看更多
登录 后发表回答