简体   繁体   中英

How to construct the POST data values in an AJAX call?

i've this piece of code that performs an AJAX call

$.ajax({
      url : 'inviaCommento.php',
      type : 'POST',
          data : {page: page, category: category} 
          dataType : 'json',
       success : function (msg)
            //...and so on

The problem is that i want to check if a search parameter is set, if yes i've to add the word to the data parameters. The question is: can i costruct the data parameters before the call appendig values to it? Something like this:

if $('#searchBtn').val()!=''
{
  data.append(search: $('#searchBtn').val())
}

Yup, but data isn't a list, it's an object, so you just assign to the appropriate key.

var data = {page:page}; // ... current value of data: param in the $.ajax call
if($('#searchBtn').val()!=='')
{
  data.search= $('#searchBtn').val();
}

You'd put this above the $.ajax() call.

Yeah, just create an array.

var data = {something: [], page: page, category: category, somekey: "default"};

data.something.push("a");
data.something.push("b");
if (...) {
    data.somekey = "new value";
}

$.ajax({
    ...
    data: data
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM