2015-05-09 62 views
1

我的形式是:如何在jquery中爲ajax post datastring設置隱藏字段的值?

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

我jQuery是:

$(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; 
}); 

我function.php是:

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

但JavaScript代碼無法發送POST變量,$ _ POST [」動作']和POST ['data_id'];

如何編輯jQuery代碼中的dataString值? 我想是這樣形成的:

data : {"action":"delete","data_id":"12456"}, 
+0

報價不匹配'值=前解析JSON字符串數據 「{」 ...' –

回答

2

更新HTML代碼如下

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

這裏發送

$(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; 
}); 
+0

謝謝,它正在工作 –

相關問題