Value pairs. I though jQuery would do it autom" />
开发者

jQuery - now: Creating an object and storing values in it to pass to an AJAX call

开发者 https://www.devze.com 2022-12-30 08:25 出处:网络
I have an array: myarr = []; I\'m filling it with some values: myarray[\'name\'] = \"Me!\"; Now I want to transform that array into a set of Key => Value pairs. I though jQuery would do it autom

I have an array:

myarr = [];

I'm filling it with some values:

myarray['name'] = "Me!";

Now I want to transform that array into a set of Key => Value pairs. I though jQuery would do it automatically, but it doesn't seem to.

$.ajax
({
    type: "POST",
    dataType: "text",
    url: "myurl",
    data: myarr
});

Is there a way to do this or something I'm doing wrong? I get no javascript errors, and no serverside errors other then no POST information at all.

I need the request to be sent as a true POST request. I need to keep the php code simple becau开发者_StackOverflowse sometimes the login won't be an AJAX call.

I'm now trying the following with an error unexepected token ':'

myarr:
{
    'name':'me'
}

The question has now become: How do I initialize a new javascript object as "blank", how do I set up mappings, and how do I pass it in an AJAX call?


The data attribute is an object, so it uses notation like so:

data: { 'Name': 'Me!' }

Not

data: ['Name':'Me!']

You need to convert your array to an object. You can easily do this in place of an array:

myData.Name = 'Me';
myData.OtherProp = 'Something';

Here's some samples:

$.ajax({
    type: 'POST',
    dataType: 'text/html',
    url: 'myUrl.php',
    data:
    {
        'Name': 'Me!'
    },
    success: function(data, status)
    {
        // data is the returned response
    }
});

OR

var myObject = new Object();

myObject.Name = 'Me!';

$.ajax({
    type: 'POST',
    dataType: 'text/html',
    url: 'myUrl.php',
    data: myObject
});

Both should get you to the right place.


You cannot pass the array directly, you need to encode it first and then pass it. For example you can use json2.js from json.org to encode it as JSON:

var mydata = JSON.stringify(myarr);
$.ajax
({
 type: "POST",
 dataType: "text",
 url: "myurl",
 data: {"mydata" : mydata}
});

Then you will need to use json_decode in PHP to convert the JSON string back to an array.

Update

To address your new questions:

How do I initialize a new javascript object as "blank"?

You can create a new object like so:

var myObj = {};

How do I set up mappings?

There are a couple different ways:

myObj.name = "Me!";
myObj['name'] = "Me!";

How do I pass it in an AJAX call?

Just pass it directly as the data argument:

data: myObj


Continue exactly like you have been, but change [ to { and ] to } (which changes your array to an object)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号