如何通过jQuery / ajax提交表单?

时间:2016-03-23 18:11:21

标签: javascript jquery ajax coldfusion

我正在尝试通过jquery提交表单,以便整个页面不会重新加载。我正在按照jQuery.post()指南的说明进行操作,但到目前为止它还没有用。以下是我正在寻找完成此任务的内容。

  1. 将表单提交到ColdFusion代理页面,然后通过CFHTTP将数据作为json发送。
  2. 在提交表单的过程中,显示​​进度gif或状态。
  3. 不知何故,隐藏或删除页面上的表单。
  4. 在以前表单的页面上显示成功或感谢信息。
  5. 到目前为止,我的表单甚至没有找到输入中的值。该错误表示“TypeError:$ form.find(...)。value不是函数”。以下是我的JavaScript代码:

    $(function(){
            $("##frmComment##").submit(function(event){
                event.preventDefault();             
                $("##submitResponse").append('<img src="http://st2.india.com/wp-content/uploads/2014/07/ajax-loader.gif" class="progressGif">');
    
    
                // Cache $form, we'll use that selector more than once
                var $form=$(this);
    
                var data = $form.serialize(); //get all the data of form
    
                //post it
                $.post(
                "/customcf/knowledgeOwl/proxyPost-KB.cfm",
                data,
                //console.log(response),                
                function(response){
                    // Success callback.  Remove your progress gif, eg:
                     //$('body').removeClass('in-progress');
                     console.log(response);
                    // Remove the spining gif from the div
                    $("##submitResponse img:last-child").remove();
                    //Remove the feedback form
                    $("##frmComment").remove();
                    $form.fadeOut('slow', function(){
                        //Add response text to the div
                        $("##submitResponse").append("<h6>Thank you for your feedback.</h6>");
                        $("##submitResponse").html(response).fadeIn('slow');
                    });
                });
    
    
                });
            })
    

    这是我在JSFiddle中设置的project。这是表格。

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    
    <form data-abide id="frmComment">
        <div class="row">
            <div class="large-12 medium-12 columns">
                <div class="row" data-equalizer>
                    <div class="large-4 medium-4 columns">
                        <div class="row">
                            <div class="large-12 columns">
                                <label>
                                    <input type="text" placeholder="Name" name="name" required>
                                </label>
                                <small class="error">Name is required and must be a string.</small>
                            </div>
                        </div>
                        <div class="row">
                            <div class="large-12 columns">
                                <label>
                                    <input type="text" placeholder="Email" name="mailfrom" required pattern='.*@.*\..{3}|.*@.*\..{2}'>
                                </label>
                                <small class="error">An email address is required.</small>
                            </div>
                        </div>
                        <div class="row">
                            <div class="large-12 columns">
                                <div class="g-recaptcha" data-sitekey="6LfjNwITABCDPbDHdC5wx6HXRmXtqO3pgUItl-E"></div>
                                <noscript>
                                    <div style="width: auto; height: 462px;">
                                        <div style="width: auto; height: 422px; position: relative;">
                                            <div style="width: auto; height: 422px; position: absolute;">
                                                <iframe src="https://www.google.com/recaptcha/api/fallback?k=6LfjNwITABCDPbDHdC5wx6HXRmXtqO3pgUItl-E" frameborder="0" scrolling="no" >
                                                </iframe>
                                            </div>
                                        </div>
                                        <div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: ##f9f9f9; border: 1px solid ##c1c1c1; border-radius: 3px; height: 100px; width: 300px;">
                                            <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 280px; height: 80px; border: 1px solid ##c1c1c1; margin: 10px; padding: 0px; resize: none;"></textarea>
                                        </div>                                                  
                                    </div>
                                    <br /><br />                                             
                                </noscript>
                            </div>
                        </div>
                    </div>
                    <div class="large-8 medium-8 columns">
                        <div class="row">
                            <div class="large-12 columns">
                                <textarea id="message" name="message" placeholder="Leave a comment...we love feedback!" rows="5"  required></textarea>                                                  
                            </div>
                        </div>
                        <div class="row">
                            <div class="large-12 columns">
                                <button type="submit" class="tiny right button">Submit</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
    <div id="submitResponse"></div>
    

    好的,在一些帮助下,我设法获取jQuery帖子将数据发送到我的proxyPost-KB.cfm页面,但是当它命中该页面时它出错(505)。这是我在proxyPost-KB.cfm页面中的内容。我在这个CFM页面中设置的日志都没有被执行。

    <!---
        Make the proxy HTTP request using. When we do this, try to pass along all of the CGI information that was made by the original AJAX request.
    --->
    <cflog text="CGI: #cgi#" type="Information" file="CGIparameters">
    <cfhttp url="https://app.kb.com/api/head/comment.json" method="post" timeout="15" throwonerror="true">
        <!---<cfhttpparam type="body" name="data"value="#serializeJSON(jsonString)#" />--->
        <cfhttpparam type="url" name="_authbykey" value="56ec1f1232131c78636142d6">
        <cfhttpparam type="url" name="project_id" value="55c4ffd123131c527e294fe6">
        <!---<cfhttpparam type="url" name="article_id" value="#artID#">
        <cfhttpparam type="url" name="content" value="#form.message#"/>
        <cfhttpparam type="url" name="public_name" value="#form.name#"/>
        <cfhttpparam type="url" name="public_email" value="#form.mailfrom#"/>--->
        <cfhttpparam type="url" name="status" value="pending"/>
    
        <!--- Pass along any URL values. --->
        <cfloop item="strKey" collection="#URL#">
            <!---<cfhttpparam type="url" name="public_name" value="#URL[strKey]#" />
            <cfhttpparam type="url" name="public_email" value="#URL[strKey]#" />--->        
            <cflog text="URL: #URL[strKey]#" type="Information" file="CGIparameters">
        </cfloop>
    </cfhttp>
    
    <!---
        Get the content as a byte array (by converting it to binary,
        we can echo back the appropriate length as well as use it in
        the binary response stream.
    --->
    <cfset binResponse = ToBinary(ToBase64( objRequest.FileContent )) />
    
    <!--- Echo back the response code. --->
    <cfheader statuscode="#Val( objRequest.StatusCode )#" statustext="#ListRest( objRequest.StatusCode, ' ' )#" />
    
    <!--- Echo back response legnth. --->
    <cfheader name="content-length" value="#ArrayLen( binResponse )#" />
    
    <!--- Echo back all response heaers. --->
    <!---<cfloop item="strKey" collection="#objRequest.ResponseHeader#">
    <!--- Check to see if this header is a simple value. --->
        <cfif IsSimpleValue( objRequest.ResponseHeader[ strKey ] )>
    
            <!--- Echo back header value. The cfheader tag generate the error "Complex object types cannot be converted to simple values"--->
            <cfheader name="#strKey#" value="#objRequest.ResponseHeader[ strKey ]#" />
            <cflog text="IsSimpleValue: #strKey#" type="Information" file="debugCFLoop">
        </cfif>
    </cfloop>--->--->
    
    <!---
        Echo back content with the appropriate mime type. By using
        the Variable attribute, we will make sure that the content
        stream is reset and ONLY the given response will be returned.
    --->
    <cfcontent type="#objRequest.MimeType#" variable="#binResponse#" />
    

2 个答案:

答案 0 :(得分:0)

以下是您所描述的例子:

$("#frmComment").submit(function(event) {
    event.preventDefault();

    // Form has been submitted - now show your progress gif, eg:
    // $('body').addClass('in-progress');
    // or maybe:
    // $('.spinner').show();
    // etc - CSS can be whatever you want

    // Cache $form, we'll use that selector more than once
    var $form=$(this);

    // Serialize all input from the form
    var data=$form.serialize();

    // Post it
    $.post(
        "your-proxy-url",
        data,
        function(response) {
            // Success callback.  Remove your progress gif, eg:
            // $('body').removeClass('in-progress');
            console.log(response); // show the proxy response on your console

            // Now hide the form
            $form.fadeOut('slow', function() {
                // And show a result once it's gone
                $(".result").html(response).fadeIn('slow');
            });
        }
    );
});

答案 1 :(得分:-1)

我认为您可以在$( "#frmComment" ).submit(function( event ) {函数中使用此代码:

event.preventDefault();
var data = $('#frmComment').serialize(); //get all the data of form
var url = "yourUrl.php";

 $.ajax({
    type: "POST",
    url: url,
    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');
    }
});

PHP&#39; yourUrl&#39;将重新显示表单输入(您可以使用var_dump($_POST);查看结构。