【问题标题】:How to get my form submitted via jQuery/ajax?如何让我的表单通过 jQuery/ajax 提交?
【发布时间】:2016-03-23 18:11:21
【问题描述】:

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

  1. 将表单提交到 ColdFusion 代理页面,然后它将通过 CFHTTP 以 json 格式发送数据。
  2. 在提交表单的过程中,显示​​进度 gif 或状态。
  3. 不知何故,隐藏或删除页面之外的表单。
  4. 在表单原来所在的页面上显示成功或感谢消息。

到目前为止,我什至没有从输入中找到值。该错误表明“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#" />

【问题讨论】:

  • TypeError 在这里,不是$form 而是$(form)
  • 啊!现在感觉有些愚蠢......我会尝试一下。
  • 好的,我试过了,它仍然给我同样的错误。另外,此页面中的示例代码api.jquery.com/jquery.post 显示了我在上面的方式。
  • 只需阅读这篇文章,它可能会为您提供解决 php 问题的指针,但表单提交在任何技术中的工作方式都相同stackoverflow.com/questions/15173965/…
  • @Sabbin $form 很好。类型错误沿着这条线发生得更远。 .value() 当然不是 jquery 方法。

标签: javascript jquery ajax coldfusion


【解决方案1】:

这里有一个例子来做你描述的事情:

$("#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');
            });
        }
    );
});

【讨论】:

  • 谢谢!我会试试看。我不知道为什么投反对票……最好给出理由。
  • 好的,这个实现有点小问题。我不想离开当前页面。我只想将表单中的数据提交到代理页面。似乎这个建议会将表单发布到代理页面,然后也离开页面。我希望用户保持在同一页面,但只提交表单。
  • 不,它不应该这样做 - event.preventDefault() 将停止提交表单。你的代码中还有那个吗?
  • 我刚刚更新了我的初始帖子,以反映我到目前为止的内容及其当前问题。
  • @Charlie123 $("##frmComment##") 不是一个有效的 jQuery 选择器 - 只有一个 '#' 代表一个 id,没有任何尾随。检查我发布的代码 - $("#frmComment")。同样,您对$("##submitResponse") 的所有使用都应该只有一个#。
【解决方案2】:

我认为您可以在 $( "#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 'yourUrl' 将接收表单输入(您可以使用 var_dump($_POST); 查看结构。

【讨论】:

    猜你喜欢
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    相关资源
    最近更新 更多