使用post方法从jQuery.ajax完整回调中发送自定义ajax请求的问题

时间:2014-12-30 09:57:18

标签: jquery ajax

我的自定义jquery插件名为form.js有问题,问题是我发送请求时内容类型的多部分表单数据请求发送成功,但是当我拨打新电话时(带有post方法)从插件的自定义回调中将post数据转换为javascript对象。所以我无法将请求数据发送到操作页面。 这是form.js

(function ( $ ) {
    $.fn.submit = function(o, sc ,cc, pc ) {

    //merge the default options with given options
    var ss = $.extend({
        placement: 'top',
        alert_type:'alert',
        redirect : false,
        reset    : false,
        refresh  : false,
        datatype : 'html',
        method : 'POST',
        cache : false,
    }, o );

    //get the current form
    //var form = document.forms[this.selector];

    var form = $(this).context;

    //get the form submit button
    //var btn = $(form)['context']['elements']['submit'];

    //var btn = $(this).context.elements.item($(this).context.length-1);
    var btn = $(this).context.elements.submit;

    //disable the submit button to stop double submitting
    $(btn).attr('disabled','disabled');
    var btn_text = $(btn).html();
    $(btn).html('Loading...');

    //get the url of the form
    var url = form.action;

    //determine the enctype of form
    var enctype = form.enctype;

    //check if multipart is set to true
    if(enctype == 'multipart/form-data'){

        $.ajaxSetup({
            contentType : false,
            processData : false,
        });

        //prepare the files data
        var data = new FormData(form);

        //prepares the post data
        $.each($(form).serializeArray(),function(k,v){          
            data.append(v.name,v.value);            
        });

    }
    else{

        //set the data if upload is not present
        //method 1
        /*var data = new Array();
        $.each(form,function(k,v){
            data[v.name] = v.value;
        });*/
        //method 2
        var data = $(form).serializeArray();
    }

    //send the request with $.ajax from now to onward

    $.ajax({
        //set the options here
        url:url,
        dataType : ss.datatype,
        method: ss.method,
        data:data,
        xhr : function(){
            myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload && pc){
                myXhr.upload.addEventListener('progress',function(prog) {
                    var value = ~~((prog.loaded / prog.total) * 100);

                    //console.log(value);
                    // if we passed a progress function
                    if(pc && typeof pc == "function") {
                        pc(prog,value);

                    // if we passed a progress element
                    } else if (pc) {
                        $(pc).val(value);
                    }
                }, false);
            }
            return myXhr;
        },
        success:function(res,textStatus){
            //shows off the progress of request
            if('function' == typeof sc){
                sc(res,form);
            }

            //enables the messaging or not with json data transmission.

            //show messages only if datatype is set to json
            if(ss.datatype == 'json'){
                //set alerts
                if(ss.alert_type == 'alert'){

                    var alert_class = '';

                    if(res.status == ''){

                        alert_class = 'alert-info';

                    }else if(res.status == true){

                        alert_class = 'alert-success';

                    }else if(res.status == false){

                        alert_class = 'alert-danger';

                    }

                    var alert_position = '';

                    if(ss.placement == 'top'){
                        alert_position = 'alert-top';
                    }else if(ss.placement == 'bottom'){
                        alert_position = 'alert-bottom';
                    }else{
                        alert_position = 'alert-top';   
                    }

                    var alert_template = '<div class="alert alert-status '+ alert_class+ ' ' + alert_position+'" id="alert-status"><button class="close" data-dismiss="alert"><i class="fa fa-times"></i></button><div class="row"><div class="container"><span>'+res.message+'</span></div></div></div>';
                    $('body').append(alert_template);   

                }
            }

            //change the button state to normal
            $(btn).removeAttr('disabled');

            $(btn).html(btn_text);

            if(ss.reset == true){
                form.reset();
            }

            if(ss.refresh == true){
                window.location.reload(true);
            }

            if(ss.redirect !== false){
                window.location.href = ss.redirect;
            }

        },
        statusCode: {
            404: function() {
                alert( "page not found" );
            }
        },
        traditional : true,
        complete : function(){
            if('function' == typeof cc){
                cc();
            }
        }
    });
};
}( jQuery ));   

index.php

<!DOCTYPE html>
<html>
<head>
    <title>Testing form.js</title>
    <link href="bootstrap.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="form.js"></script>
    <script type="text/javascript" src="bootstrap.js"></script>
    <script type="text/javascript">
    $(document).on('submit','#a_form',function(e){
        e.preventDefault();
        $('form',this).submit({
            alert_type : false,
            reset : false,
            datatype : 'html',
        },function(r){
            //this is the success callback
            $('.response1').html(r);
        },function(){
            //this is the complete callback
            //send a new request to action.php with post method
            $('.response2').load('action.php',{name:'ahmed'});
        },function(progress,value){
            $('.progress').append(value);
        });
    })
    </script>
</head>
<body>
    <div class="container">
        <div class="col-md-6">
            <form class="form-horizontal" name="a_form" id="a_form" action="action.php" method="post" enctype="multipart/form-data">
                <input type="text" name="name" id="name" class="form-control"><br/>
                <input type="text" name="age" id="age" class="form-control"><br/>
                <input type="text" name="email" id="email" class="form-control"><br/>
                <input type="text" name="gender" id="gender" class="form-control"><br/>
                <input type="text" name="address" id="address" class="form-control"><br/>
                <input type="file" name="photo" id="photo" class="form-control"><br/>
                <input type="file" name="file" id="file" class="form-control"><br/>
                <button type="submit" class="btn btn-default">Submit</button>
            </form>
        </div>
        <div class="col-md-5 well response1"></div>
        <div class="col-md-5 well response2"></div>
        <div class="col-md-1 well progress"></div>
    </div>
    </body>
</html>

Action.php很简单

<pre>
    <?php
    print_r($_POST);
    print_r($_FILES);
    ?>
</pre>

当我从插件的完整回调中发送另一个帖子请求时,会出现问题。 有什么建议, 在Adavance感谢

1 个答案:

答案 0 :(得分:1)

如果是添加

$.ajaxSetup({
    contentType : false,
    processData : false,
});

之前的这些代码行

var data = $(form).serializeArray();

这段代码一切正常。这意味着我的代码中出现了contentType和processData的错误。