$ _POST无法以ajax形式提交? [英] $_POST is not working in ajax form submit?

查看:74
本文介绍了$ _POST无法以ajax形式提交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试通过ajax表单提交检查用户输入名称时!它只能在 sessions.php中获得未定义索引:用户名 ,缺少什么?

When I try to check user input name is already exist by ajax form submit !But it only get Undefined index: username in sessions.php ,what is missing ?

<form action="" method="POST" id="saveuser" enctype="multipart/form-data">
<input type="text" name="username"><br>
<input type="password" name="pass"><br>
<input type="file" name="fileupload"><br>
<input type="submit" name="submit" value="Confirm" id="confirm">
</form>
<script type="text/javascript">
    $('#confirm').click(function(e){
        e.preventDefault();
      $.ajax({
            type:'POST',
            url :"sessions.php",
            data:$("#saveuser").serialize(),
            contentType : false,
            processData: false,            
            success: function(d){
                console.log(d);//[error] :Undefined index: username 
            }
        });
    });
</script>

sessions.php

sessions.php

<?php
$exist = "david";
if($_POST['username'] == $exist){
    echo json_encode("Already exist");
}
else{
    echo json_encode("You can succesfully add");
}
?>


推荐答案

您的代码存在一些问题,例如:

There are few issues with your code, such as:



...它只获得未定义的索引:sessions.php中的用户名

... it only get Undefined index: username in sessions.php

问题在于以下两行,

contentType : false,
processData: false,

来自文档


contentType (默认:'application / x-www-form-urlencoded; charset = UTF-8'

键入:布尔值字符串

将数据发送到服务器时,请使用此内容类型。默认为application / x-www-form-urlencoded; charset = UTF-8,这在大多数情况下都适用。如果您明确地将内容类型传递给 $ .ajax(),那么它总是被发送到服务器(即使没有数据发送)。从jQuery 1.6开始,您可以传递 false 来告诉jQuery不设置任何内容类型标头。

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: Boolean or String
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header.


processData (默认值: true

类型:布尔值

默认情况下,作为对象传入数据选项的数据(技术上,不是字符串)将被处理并转换为查询字符串,适合默认的 content-typeapplication / x -www窗体-urlencoded即可。如果要发送DOMDocument或其他未处理的数据,请将此选项设置为 false

processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

因此,如果设置 contentType, sessions.php 页面中的 $ _ POST 数组将为空 processData false ,这就是为什么你得到这个 undefined index:用户名错误。但话说回来,既然你发送了一个包含AJAX请求的文件,可以将这些设置设置为 false ,这将在下面进一步说明。

Hence, $_POST array would be empty in sessions.php page if you set contentType and processData to false, and that's why you're getting this undefined index: username error. But having said that, since you're sending a file with your AJAX request, it's okay to set these settings as false, which is further explained in the following point.

.serialize() 方法通过序列化表单控件值来创建URL编码的文本字符串,例如< input> < textarea> < select> 。但是,在序列化表单时它不包含文件输入字段,因此远程AJAX处理程序根本不会接收文件。因此,如果您通过AJAX上传文件,请使用 FormData 对象。但请记住,旧浏览器不支持FormData对象。 FormData支持从以下桌面浏览器版本开始:IE 10 +,Firefox 4.0 +,Chrome 7 +,Safari 5 +,Opera 12 +。

.serialize() method creates a URL encoded text string by serializing form control values, such as <input>, <textarea> and <select>. However, it doesn't include file input field while serializing the form, and hence your remote AJAX handler won't receive the file at all. So if you're uploading file through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object. FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.

自从你'期待来自服务器的json对象,将此设置 dataType:'json'添加到您的AJAX请求中。 dataType 是您期望从服务器返回的数据类型。

Since you're expecting a json object from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server.

所以解决方案是这样的:

So the solution would be like this:

保持您的 HTML 表单,并更改您的 jQuery / AJAX 脚本按以下方式,

Keep your HTML form as it is, and change your jQuery/AJAX script in the following way,

$('#confirm').click(function(e){
    e.preventDefault();

    var formData = new FormData($('form')[0]);
    $.ajax({
        type: 'POST',
        url : 'sessions.php',
        data: formData,
        dataType: 'json',
        contentType: false,
        processData: false,            
        success: function(d){
            console.log(d.message);
        }
    });
});

sessions.php 页面上,处理您的表单如下:

And on sessions.php page, process your form like this:

<?php

    $exist = "david";
    if(isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['pass']) && !empty($_POST['pass'])){
        if($_POST['username'] == $exist){
            echo json_encode(array("message" => "Already exist"));
        }else{
            echo json_encode(array("message" => "You can succesfully add"));

            // get username and password
            $username = $_POST['username'];
            $password = $_POST['pass'];

            // process file input
            // Check whether user has uploaded any file or not
            if(is_uploaded_file($_FILES['fileupload']['tmp_name'])){

                // user has uploaded a file

            }else{
                // no file has been uploaded
            }
        }
    }else{
        echo json_encode(array("message" => "Invalid form inputs"));
    }

?>

这篇关于$ _POST无法以ajax形式提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆