简体   繁体   English

使用jQuery进行Ajax调用并在表单提交时更新元素

[英]using jquery to make ajax call and update element on form submit

Here is my html form 这是我的HTML表格

    <div id=create>
        <form action=index.php method=get id=createform>
        <input type=text name=urlbox class=urlbox>
        <input type=submit id=createurl class=button value=go>
        </form>
    </div>
    <div id=box>
        <input type=text id=generated value="your url will appear here">
    </div>

Here is the javascript im trying to use to accomplish this; 这是试图用来完成此任务的javascript im;

$(function () {
    $("#createurl").click(function () {
        var urlbox = $(".urlbox").val();
        var dataString = 'url=' + urlbox;

            if (urlbox == '') {
                alert('Must Enter a URL');
            }else{
                $("#generated").html('one moment...');
                $.ajax({
                    type: "GET",
                    url: "api-create.php",
                    data: dataString,
                    cache: false,
                    success: function (html) {
                        $("#generated").prepend(html);
                    }
                });
            }return false;
    });
});

when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown. 当我单击提交按钮时,什么也没有发生,没有错误,并且没有显示api-create.php的返回数据。

the idea is that the new data from that php file will replace the value of the textbox in the #box div. 这个想法是,来自该php文件的新数据将替换#box div中文本框的值。

i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this 我正在使用Google的jquery,并且在手动执行get请求时php文件有效,因此我将其缩小为

Because you're binding to the submit click instead of the form's submit.. try this instead: 因为您要绑定到提交单击而不是表单的提交,所以请尝试以下操作:

$('#createForm').submit(function() {

// your function stuff...

return false; // don't submit the form

});

There is great jQuery plugin called jQuery Form Plugin . 有一个很棒的jQuery插件,称为jQuery Form Plugin All you have to do is just: 您所要做的就是:

$('#createform').ajaxForm(
    target: '#generated'
});   

Dan's answer should fix it. 丹的答案应该可以解决。 However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this: 但是,如果#createurl不是提交/输入按钮,而是使用CSS等样式的链接,则可以执行以下操作:

$('#createurl').click(function () {
  $('#createForm').submit();
});

$('#createForm').submit(function () {
  // all your function calls upon submit
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM