使用POST将JavaScript变量传递给PHP

时间:2015-04-30 11:42:33

标签: javascript php jquery ajax

我在某处读到,在使用ajax时,您不需要表单或隐藏值来传递数据。如果我能得到一个例子,我将不胜感激。

index.js:

function collectData(r) { 
    //gets the rows index
    var i = r.parentNode.parentNode.rowIndex;
    //selects the row picked
    var sliceRow = document.getElementById('Sona').rows[i];
    //have access to indiviual cells in the row
    var sliceCell = sliceRow.cells;
    var song = (sliceCell[0].innerHTML);
    var artist = (sliceCell[1].innerHTML);
    $.post("myLibrary.php", { postsong: song, postartist: artist });
}

PHP文件:

if (isset($_POST)) {
    $song = $_POST['postsong'];
    echo $song;
}

1 个答案:

答案 0 :(得分:-1)

    $.ajax({
        url  : example.com', 
        contentType : 'application/x-www-form-urlencoded',
        type : 'post',
        data : {
         i         : r.parentNode.parentNode.rowIndex,
         sliceRow  : document.getElementById('Sona').rows[i],
         sliceCell : sliceRow.cells,
         song      : (sliceCell[0].innerHTML),
         artist    : (sliceCell[1].innerHTML),
        },
        success:function(data) {
            // blabla
        }, 
    });


    <?php

    if(isset($_POST)) {
        print_r($_POST);
    }