2014-04-06 55 views
0

我很努力從我的php代碼中讀取來自ajax post的發佈數據。 我既不是PHP專家,也不是Jquery,幾周前我就學會了。很抱歉,如果我還沒有使用所有的術語。我從ajax序列化數據,因爲我的表單中會有更多的字段。爲了清楚起見,我僅顯示一個字段。 我試圖讀取每個變量,例如在這種情況下的評論, 我只是嘗試print_r($ _ POST),我得到錯誤。 我看不到如何做,可能是一個轉換或語法錯誤。 我將不勝感激任何見解操縱序列化ajax數據到php

PHP文件

public function ajaxSave($post_id) 
    { 

    print_r($_POST);  

} 

jQuery腳本

$('body').on('click','#saveComment',function(e) { 


      $("#comment-form").submit(function(e) { 
       var postData = $(this).serialize(); 
       alert(postData); 
       $.ajax( 
       { 
        url : "ajaxSave.php", 
        type: "POST", 
        data : postData, 
        dataType:"json", 
        success:function(data) 
         { 
          alert('success'); 
         }, 
        error: function(jqXHR, textStatus, errorThrown) 
         { 
          alert("error"); 
         } 
       }); 
       e.preventDefault(); //STOP default action 
       }); 
      $("#comment-form").submit(); 
     }); 

<input id="Comment_comment" type="text" name="Comment[comment]" maxlength="140" size="60"> 

在Firebug

在標籤後,我有

Comment[comment] mycomment 
Comment[post_id] 16 

來源

Comment%5Bcomment%5D=mycomment&Comment%5Bpost_id%5D=16 

在HTML標籤,我有

Array ([Comment] => Array ([comment] => for [post_id] => 16)) 
+1

你忘了更換print_r($_POST);引用url參數 – adeneo

+0

是的,謝謝你,在我的代碼中它被編碼以便調用php代碼,我在我的重新編碼@adeneo – trinocle

+0

中犯了一個錯誤,但是它仍然存在錯誤 – trinocle

回答

0

你期待JSON回,但返回了的印刷品超全球化,這是一個parseError。

刪除數據類型,且日誌打印到控制檯看到它

$('body').on('click', '#saveComment', function (e) { 
    e.preventDefault(); 
    $("#comment-form").trigger('submit'); 
}); 

$("#comment-form").submit(function(e) { 
    e.preventDefault(); 
    var postData = $(this).serialize(); 
    alert(postData); 
    $.ajax({ 
     url: "ajaxSave.php", 
     type: "POST", 
     data: postData, 
     success: function (data) { 
      console.log(data) 
     }, 
     error: function (jqXHR, textStatus, errorThrown) { 
      alert("error"); 
     } 
    }); 
}); 

不要綁定一個click事件

0

內提交事件與echo json_encode($_POST);