开发者

storing list item code in database

开发者 https://www.devze.com 2023-04-01 22:15 出处:网络
i have the following structure: <ul> <li code=12>C++</li> <li code=5>Java</li>

i have the following structure:

<ul>
<li code=12>C++</li>
<li code=5>Java</li>
<li code=17>PHP</li>
</ul>

when the user click on save button the form will be submit 开发者_如何学Cto PHP function.

i want to pass 12,5,17(list item codes) as array to PHP function(with $_POST array) to store it in the database.

what is the best way to do this?


// Event handler for when you click the button
$("button.save").click(function () {
    var codes = [];

    // For each of your li's with a code attribute
    $("li[code]").each(function () {

        // Stuff the code into an array
        codes.push($(this).attr("code"))
    });

    // You can't post an array, so we turn it into a comma separated string
    codes = codes.join();

    // Do a post request to your server resource
    $.post("/path-to-your-php-code/", {"codes" : codes}, function (response) {
        // Handler for successful post request

        alert("The ajax request worked!");
    });

});

You will also need to parse the string of codes in your php, which will be available in

$_POST["codes"];


$.post('url.php', {
      li1:$("li:eq(0)").text(),
      li2:$("li:eq(1)").text(),
      li3:$("li:eq(2)").text()}, function(){
   alert('done');
});


Extending on @Adam's answer, to pass the data in a way that PHP will recognize as an array, you can use the fact that in HTTP you can POST the same key with more than one value. I've noticed empirically that PHP treats multi-valued keys terminating with "[]" as arrays. So, you can use this (untested) code to accomplish your original goal:

// Event handler for when you click the button
$("button.save").click(function () {
    var codes = [];

    // For each of your li's with a code attribute
    $("li[code]").each(function () {

        // Stuff the code into an array
        codes.push($(this).attr("code"));
    });

    // >>>>> Set up the post data to be recognized as an array by PHP
    var post_data = [];
    $(codes).each(function() {
        post_data.push({
            name: "codes[]",
            value: this
        });
    });

    // Do a post request to your server resource
    $.post("/path-to-your-php-code/", post_data, function (response) {
        // Handler for successful post request

        alert("The ajax request worked!");
    });

});
0

精彩评论

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