基本的ajax / jquery POST失败

时间:2016-09-08 14:30:09

标签: php jquery json ajax post

自从我触及jQuery(事实上几年)以来已经有一段时间了,所以请原谅无知。

我无法将以下基本jQuery帖子发送到PHP脚本中:

<!DOCTYPE html>
<html><body>
<form id="formID">
    <input name="name" type="text" id="name">
    <input name="email" type="text" id="email">
    <input name="mobile" type="text" id="mobile">
    <div id="submitButton">Submit</div>
    <div id="result"></div>
</form>

<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script>
        $("#submitButton").click(function(e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "/fupload",
                /*data: $("#formID").serialize(),*/
                data: {name: "bob"},
                success: function(resp) {
                    //$('#result').html(resp);
                    console.log(resp);
                }
        });
    });
</script>
</body></html>

和/fupload/index.php脚本:

<?php

$idInfo = "[ " . $_POST['name'] . ':' . $_POST['email'] . ':' . $_POST['mobile'] . " ]";
echo $idInfo;
return;

未定义PHP $ _POST变量(根据控制台输出)。在实际表单数据上使用serialize()也会导致$ _POST变量未被定义。如果我更改为GET方法,那么它可以工作,但我需要发布。

我很感激任何关于我犯下的愚蠢错误的指示。

由于

3 个答案:

答案 0 :(得分:0)

ajax的设置应为method而不是type

$.ajax({
    method: "POST", 
  //^^^^^---- here you have defined as type   
    .......
})

答案 1 :(得分:0)

通过此

获取$ _POST
$dataString = $_POST['datapost'];
parse_str($dataString, $dataArray); print_r($dataArray);

答案 2 :(得分:0)

/之后添加/fupload,如下所示:

url: "/fupload/",

这将正确运行您的代码。如果您最后不使用/,则会向您的php脚本发送格式错误的请求。由于post请求值也是使用查询字符串发送的。

完整代码:

<script>
    $("#submitButton").click(function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "/fupload/",
            /*data: $("#formID").serialize(),*/
            data: {name: "bob"},
            success: function(resp) {
                //$('#result').html(resp);
                console.log(resp);
            }
    });
});
</script>
相关问题