使用jQuery向服务器提交变量

时间:2022-11-23 20:26:53

I'm trying to figure out how to submit my form with a page refresh. I'm creating a small dealer locator for a client, and when my form submits, they update the dealer list fine. What I'm trying to do is have it so the page doesn't reload. So far I've written the following code, but not sure how to post the variable and have it take effect by my Ruby on Rails code.

我想弄清楚如何在页面刷新时提交我的表单。我正在为客户创建一个小的经销商定位器,当我的表单提交时,他们会很好地更新经销商列表。我要做的是让页面不重载。到目前为止,我已经编写了以下代码,但不确定如何发布该变量并让它在Ruby on Rails代码中生效。

$("#getDealers ").submit(function(e) {
    e.preventDefault();

    // pull in postal code variable


});

1 个解决方案

#1


3  

You could use the .serialize() method to send the contents of the form using AJAX to the corresponding action as if it was normal request:

您可以使用.serialize()方法将表单的内容以AJAX的形式发送给相应的操作,就好像这是正常的请求:

$('#getDealers').submit(function(e) {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function(result) {
            // TODO: do something with the result returned by the server
        }
    });
    e.preventDefault();
});

And to avoid writing all this code you could use the excellent jquery form plugin:

为了避免编写所有这些代码,您可以使用优秀的jquery表单插件:

$(function() {
    // AJAXify the getDealers form
    $('#getDealers').ajaxForm(function(result) {
        // TODO: do something with the result returned by the server
    });
});

#1


3  

You could use the .serialize() method to send the contents of the form using AJAX to the corresponding action as if it was normal request:

您可以使用.serialize()方法将表单的内容以AJAX的形式发送给相应的操作,就好像这是正常的请求:

$('#getDealers').submit(function(e) {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function(result) {
            // TODO: do something with the result returned by the server
        }
    });
    e.preventDefault();
});

And to avoid writing all this code you could use the excellent jquery form plugin:

为了避免编写所有这些代码,您可以使用优秀的jquery表单插件:

$(function() {
    // AJAXify the getDealers form
    $('#getDealers').ajaxForm(function(result) {
        // TODO: do something with the result returned by the server
    });
});