[英]Jquery AJAX post to PHP
好的,我已經建立了我的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");
}
});
});
在我的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);
?>
這應該這樣做:
...
$.ajax({
type: "POST",
url: "order.php",
data: { 'dataString': dataString },
cache: false,
success: function()
{
alert("Order Submitted");
}
});
您可以嘗試驗證:
<?php
$stringData = $_POST['dataString'];
echo $stringData;
?>
你為什么不嘗試像這樣構建你的數據
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
});
然后在你的AJAX調用中
data: postData,
現在,您的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
}
}
首先將json對象轉換為js中的字符串,如下所示:
var json_string=JSON.stringify(json_object);
然后,將其作為字符串傳遞給PHP,然后在php中解碼它,如下所示:
<?php
$map = json_decode($_POST['json_string']);
?>
我希望這有助於任何人找到這個帖子......
問題是您正在嘗試訪問一個名為“dataString”的POST變量,該變量不存在。 僅僅因為您將“data”屬性設置為名為“dataString”的變量的內容並不意味着您的post變量將被稱為“dataString”。
你可以試試這個:
data: { "dataString": dataString },
這會將對象傳遞給jQuery函數,該函數具有名為“dataString”的屬性以及實際數據字符串的值。 jQuery將獲取此對象的所有屬性(在本例中只是一個),並將它們設置為最終將發送到PHP應用程序的HTTP請求的post變量。 這允許您通過$ _POST [“dataString”]調用訪問數據。
史蒂夫
我在使用時遇到問題:
url: "/folder/form.php",
我必須使用:
url: "folder/form.php",,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.