2015-10-19 18 views
-1

我有這樣的Ajax調用就像這樣:jQuery和PHP的Ajax調用返回空十歲上下

$.ajax({ 
    type: "POST", 
    url: "insertController.php", 
    data: $('form').serialize(), 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function (data) { 
     alert('Success, you\'re data has been saved!'); 
    }, 
    failure: function (errMsg) { 
     alert('Failed, somthing went wrong, please try again!'); 
    } 
}); 

的數據是這樣的:

name=James&email=test%40yahoo.com&7%3A00pm=on 

,但在PHP結束(insertController.php)

我試試這個:

print_r($_POST); 

它返回

Array() 

我的ajax調用中的數據有什麼問題嗎?

+1

你'的contentType: 「應用/ JSON的;字符集= UTF-8」,'沒有按不匹配你發送給php的數據。 –

+0

'contentType'行設置* request *有效載荷的Content-type頭部!您不會將JSON發送到您的服務器,請刪除該行。 –

回答

2

data參數接受一個Javascript對象,而不是查詢字符串,所以你需要使用$form.serializeArray()代替serialize();

$.ajax({ 
    type: "POST", 
    url: "insertController.php", 
    data: $('form').serializeArray(), 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function (data) { 
     alert('Success, you\'re data has been saved!'); 
    }, 
    failure: function (errMsg) { 
     alert('Failed, somthing went wrong, please try again!'); 
    } 
});