如何在jquery中为ajax post datastring设置隐藏字段的值?

时间:2015-05-09 17:08:43

标签: javascript php jquery ajax

我的表格是:

views.html

我的jQuery是:

<form method="POST">
<input type="hidden" name="params" id="defaultform" value="{"action":"delete","data_id":"123456"}" />
</form>

我的function.php是:

$(document).on('click', '#deleteItem', function(e) {

    var dataString = $('#defaultform').val();

    $.ajax({
        type: "POST",
        url: "functions.php",
        data: dataString,
        cache: false,
        success: function(data){
            var response = $.parseJSON(data);
            if (response.totalrecords > 0) {
                alert(response.totalrecords);
            }
        }
    });
    return false;
});

但JavaScript代码无法发送POST变量,$ _POST ['action']和POST ['data_id'];

如何在jQuery代码中编辑dataString值? 我希望这样形成:

$action = $_POST['action'];
$data_id = $_POST['data_id'];
//some php codes
$response = array('totalrecords' => $count);
echo json_encode($response);

1 个答案:

答案 0 :(得分:2)

更新您的html代码,如下所示

<form method="POST">
<input type="hidden" name="params" id="defaultform" value='{"action":"delete","data_id":"123456"}' />
<!--                                                    --^--------------------------------------^----     -->
</form>

在发送

之前解析JSON字符串数据
$(document).on('click', '#deleteItem', function(e) {

    var dataString = JSON.parse($('#defaultform').val());
    //             -----^-----

    $.ajax({
        type: "POST",
        url: "functions.php",
        data: dataString,
        cache: false,
        success: function(data){
            var response = $.parseJSON(data);
            if (response.totalrecords > 0) {
                alert(response.totalrecords);
            }
        }
    });
    return false;
});