简体   繁体   中英

Sending an array to php through ajax

I have a checkbox list of items. I need to update my database to which items were selected. The list of items is displayed dynamically.

The problem is how can i pass list of ID's through ajax?

here is my ajax code:

function update(form,div,PhpFile,type)
{
if (request)
    {
        var obj = document.getElementById(divId);
        request.open("POST",PhpFile);
        //setting the header
        request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

        request.onreadystatechange = function()
        {   
            if (request.readyState == 4 &&
                    request.status == 200){
                obj.innerHTML =request.responseText;
            }
        }

        if(type=='news')
            request.send(?????);

    }
}

I've marked with??? the space that I don't know what to put there.

Of course I can update each of the check boxes individually but it is a very bad solution.

PHP 5 can decode JSON and in JS you will need to use a library. This seems to be a popular answer.

Serializing to JSON in jQuery

And JSON in PHP http://www.php.net/manual/en/function.json-decode.php

I think you can serialize the array in JavaScript, pass it as a string with AJAX, and then unserialize it in PHP. Either that or convert the array values to a delimited string (comma or pipe separated) and then explode that string in PHP. That leaves your transmitted data human readable, which is nice for debugging.

Convert the array to JSON with JSON.stringify() , send it, then convert the JSON string back to an object in PHP with json_decode() .

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