jquery& PHP Ajax调用返回empty-ish

时间:2015-10-19 14:40:59

标签: php jquery ajax

我有这样的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 个答案:

答案 0 :(得分: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!');
    }
});