ben*_*e89 7 php ajax jquery post json
好的,我已经建立了我的json字符串,但我不知道下一步该做什么?
$('#submit').live('click',function(){
var dataString = '[';
$('#items tr').not(':first').each(function(){
var index = $('#items tr').index(this);
var supp_short_code=$(this).closest('tr').find('.supp_short_code').text();
var project_ref=$(this).closest('tr').find('.project_ref').text();
var om_part_no=$(this).closest('tr').find('.om_part_no').text();
var description=$(this).closest('tr').find('.description').text();
var cost_of_items=$(this).closest('tr').find('.cost_of_items').text();
var cost_total=$(this).closest('tr').find('.cost_total').text();
dataString += '{"row":"' + index + '", "supp_short_code":"' + supp_short_code + '", "project_ref":"' + project_ref + '", "om_part_no":"' + om_part_no + '", "description":"' + description + '", "cost_of_items":"' + cost_of_items + '", "cost_total_td":"' + cost_total + '"}';
});
dataString += ']';
$.ajax
({
type: "POST",
url: "order.php",
data: dataString,
cache: false,
success: function()
{
alert("Order Submitted");
}
});
});
Run Code Online (Sandbox Code Playgroud)
在我的php文件中,我试图将dataString写入文本文件,所以我可以看到它通过确定但文本文件中没有任何内容!?我做错了客户端或PHP端,我的PHP代码:
<?php
$stringData = $_POST['dataString'];
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $stringData);
fclose($fh);
?>
Run Code Online (Sandbox Code Playgroud)
jer*_*jer 10
这应该这样做:
...
$.ajax({
type: "POST",
url: "order.php",
data: { 'dataString': dataString },
cache: false,
success: function()
{
alert("Order Submitted");
}
});
Run Code Online (Sandbox Code Playgroud)
您可以尝试验证:
<?php
$stringData = $_POST['dataString'];
echo $stringData;
?>
Run Code Online (Sandbox Code Playgroud)
你为什么不尝试像这样构建你的数据
var postData = {};
$('#items tr').not(':first').each(function(index, value) {
var keyPrefix = 'data[' + index + ']';
postData[keyPrefix + '[supp_short_code]'] = $(this).closest('tr').find('.supp_short_code').text();
postData[keyPrefix + '[project_ref]'] = $(this).closest('tr').find('.project_ref').text();
// and so on
});
Run Code Online (Sandbox Code Playgroud)
然后在你的AJAX调用中
data: postData,
Run Code Online (Sandbox Code Playgroud)
现在,您的PHP脚本可以将数据作为多维数组处理
<?php
if (isset($_POST['data']) && is_array($_POST['data'])) {
foreach ($_POST['data'] as $row => $data) {
echo $data['supp_short_code'];
echo $data['project_ref'];
// and so on
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
57353 次 |
最近记录: |