简体   繁体   English

以表格形式提交AJAX / Javascript,然后提交

[英]AJAX/Javascript In a Form and then submit it

I'm php developer starting to get heavier into ajax and I've come across a problem I am not sure how to solve. 我是php开发人员,开始越来越沉重地使用ajax,遇到了一个我不确定如何解决的问题。

I am creating a form on the fly like this: 我正在像这样动态创建表单:

function addSearchResult(label, tz) {
    var html = '';
    html += '<div>'
    html += '<form id="product-form" >';
    html += '<div class="clock">'
    html += '<div class="hour"></div>'
    html += '<div class="min"></div>'
    html += '<div class="sec"></div>'
    html += '<input type="text" id="label" name="Label" placeholder="Label">'
    html += '</div>'
    html += '<div class="city">GMT</div>'
    html += '<a href="#" class="whiteButton submit" id="view-product-button" >View</a>'
    html += '</form>'
    html += '</div>'
    var insert = $(html);
    $('#search-results').append(insert.data('tz_offset', tz).find('.city').html(label).end());
}

And I am reading the form results like this: 我正在阅读这样的表单结果:

$('#product-form').submit(function() {
    alert('OK');
    addProduct('Test Value', 'Test Produlct');
    $('input').blur();
    $('#add .cancel').click();
    this.reset();
    return false;
});

The problem is, it does not work. 问题是,它不起作用。 If I put the form directly in the html it works fine. 如果我将表单直接放在html中,则效果很好。 But adding it through ajax, it will not pick up that the form exist. 但是通过ajax添加它,将不会发现该表单存在。

How should I go about solving this problem? 我应该如何解决这个问题?

Using the shortcut event handlers (eg submit() or click() ) only works for elements which are placed in the DOM on page load. 使用快捷方式事件处理程序(例如submit()click() )仅适用于页面加载时放置在DOM中的元素。

For dynamically added elements, you need to use delegate() , or on() for jQuery 1.7+. 对于动态添加的元素,您需要对jQuery 1.7+使用delegate()on() Try this: 尝试这个:

< jQ 1.7 <jQ 1.7

$('#search-results').delegate('#product-form', 'submit', function() {
    // rest of your code
});

jQ 1.7+ 智商1.7+

$('#search-results').on('submit', '#product-form', function() {
    // rest of your code
});

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

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