Javascript 提交表单并使用 jQuery 获取 JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2960321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:41:21  来源:igfitidea点击:

Submit a form and get a JSON response with jQuery

javascriptjqueryforms

提问by Leopd

I expect this is easy, but I'm not finding a simple explanation anywhere of how to do this. I have a standard HTML form like this:

我希望这很容易,但我没有在任何地方找到关于如何做到这一点的简单解释。我有一个像这样的标准 HTML 表单:

<form name="new_post" action="process_form.json" method=POST>
      <label>Title:</label>
      <input id="post_title" name="post.title" type="text" /><br/>

      <label>Name:</label><br/>
      <input id="post_name" name="post.name" type="text" /><br/>

      <label>Content:</label><br/>
      <textarea cols="40" id="post_content" name="post.content" rows="20"></textarea>
    <input id="new_post_submit" type="submit" value="Create" />
</form>

I'd like to have javascript (using jQuery) submit the form to the form's action (process_form.json), and receive a JSON response from the server. Then I'll have a javascript function that runs in response to the JSON response, like

我想让 javascript(使用 jQuery)将表单提交给表单的操作(process_form.json),并从服务器接收 JSON 响应。然后我将有一个响应 JSON 响应而运行的 javascript 函数,例如

  function form_success(json) {
     alert('Your form submission worked');
     // process json response
  }

How do I wire up the form submit button to call my form_success method when done? Also it should override the browser's own navigation, since I don't want to leave the page. Or should I move the button out of the form to do that?

完成后如何连接表单提交按钮以调用我的 form_success 方法?它也应该覆盖浏览器自己的导航,因为我不想离开页面。或者我应该将按钮移出表单才能做到这一点?

回答by Guffa

If you want to get the response in a callback, you can't post the form. Posting the form means that the response is loaded as a page. You have to get the form data from the fields in the form and make an AJAX request.

如果您想在回调中获得响应,则无法发布表单。发布表单意味着响应被加载为一个页面。您必须从表单中的字段获取表单数据并发出 AJAX 请求。

Example:

例子:

$(function(){
  $('form[name=new_post]').submit(function(){
    $.post($(this).attr('action'), $(this).serialize(), function(json) {
      alert(json);
    }, 'json');
    return false;
  });
});

Notice that you have to return falsefrom the method that handles the submit event, otherwise the form will be posted also.

请注意,您必须false从处理提交事件的方法中返回,否则表单也会被发布。

回答by Anpher

If you need POST request use jQuery.post()passing the fourth argument "json"

如果您需要 POST 请求,请使用jQuery.post()传递第四个参数“json”

$(function(){
  $("form").submit(function(){
    $.post($(this).attr("action"), $(this).serialize(), function(jsonData){
      console.log(jsonData);
    }, "json");
  });
});

Guffa was faster than me :)

Guffa 比我快 :)

回答by gurun8

Have you tried using .getJSON()and .serialize()?

你试过使用.getJSON().serialize()吗?

$('form').submit(function() {
    $.getJSON('ajax/test.json?' + $(this).serialize(), function(data) {
      $('.result').html('<p>' + data.foo + '</p>'
        + '<p>' + data.baz[1] + '</p>');
    });
});