使用 jQuery 和 PHP 序列化和提交表单

2022-08-30 10:21:34

我正在尝试使用jQuery发送表单的数据。但是,数据不会到达服务器。你能告诉我我做错了什么吗?

我的 HTML 表单:

<form id="contactForm" name="contactForm" method="post">
    <input type="text" name="nume" size="40" placeholder="Nume">
    <input type="text" name="telefon" size="40" placeholder="Telefon">
    <input type="text" name="email" size="40" placeholder="Email">
    <textarea name="comentarii" cols="36" rows="5" placeholder="Message"></textarea> 
    <input id="submitBtn" type="submit" name="submit" value="Trimite">
</form>


JavaScript(与上述形式相同的文件):

<script type="text/javascript">
    $(document).ready(function(e) {

        $("#contactForm").submit(function() {
            $.post("getcontact.php", $("#contactForm").serialize())
            // Serialization looks good: name=textInNameInput&&telefon=textInPhoneInput etc
            .done(function(data) {
                if (data.trim().length > 0) {
                    $("#sent").text("Error");   
                } else {
                    $("#sent").text("Success");
                }
            });

            return false;
        })
    });
</script>


服务器端 PHP (/getcontact.php):

$nume = $_REQUEST["nume"]; // $nume contains no data. Also tried $_POST
$email = $_REQUEST["email"];
$telefon = $_REQUEST["telefon"];
$comentarii = $_REQUEST["comentarii"];


你能告诉我我做错了什么吗?


更新

已选中并返回一个空数组。var_dump($_POST)

奇怪的是,在我的本地机器上测试的相同代码工作正常。如果我将文件上传到我的托管空间,它将停止工作。我尝试在不使用jQuery的情况下做一个老式的表单,所有数据都是正确的。

我不明白这怎么会是服务器配置问题。有什么想法吗?

谢谢!


答案 1

您可以使用此功能

var datastring = $("#contactForm").serialize();
$.ajax({
    type: "POST",
    url: "your url.php",
    data: datastring,
    dataType: "json",
    success: function(data) {
        //var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
        // do what ever you want with the server response
    },
    error: function() {
        alert('error handling here');
    }
});

返回类型为 json

编辑:我使用event.preventDefault来防止浏览器在这种情况下被提交。

向答案添加更多数据。

dataType: "jsonp"如果是跨域调用。

beforeSend:这是一个预请求回调函数

complete:在请求后调用的函数 ends.so 无论成功或错误如何都必须执行的代码都可以转到此处

async:默认情况下,所有请求都是异步发送的

cache:默认情况下为 true。如果设置为 false,它将强制浏览器不缓存请求的页面。

在此处查找官方页面


答案 2

您可以使用表单数据添加额外的数据

使用序列化数组并添加其他数据:

var data = $('#myForm').serializeArray();
    data.push({name: 'tienn2t', value: 'love'});
    $.ajax({
      type: "POST",
      url: "your url.php",
      data: data,
      dataType: "json",
      success: function(data) {
          //var obj = jQuery.parseJSON(data); if the dataType is not     specified as json uncomment this
        // do what ever you want with the server response
     },
    error: function() {
        alert('error handing here');
    }
});

推荐