Use array as jQuery POST variables?

When sending data via POST or GET using jQuery, you use for the format { name:"value" }, so I wondered if there was a way to do this with this code:

var postdata = array();
postdata['name'] = "data";
$.post("page.php", postdata, function(data)
{
    alert(data);
}

I tried this and it does not seem to work. Is there any way to do this?

+3
source share
1 answer

What you are trying to initialize is an object, not an array. You can initialize objects in two ways:

var postdata = {};

Or:

var postdata = new Object();

Then you can assign keys and values ​​in the same way as you:

postdata['name'] = "data";

Or:

postdata.name = "data";

You can also create your object at the initialization stage:

postdata = {
    name: "data"
}
+1
source

Source: https://habr.com/ru/post/1736698/


All Articles