开发者

Referencing JSON response to POST of form data with jQuery and the Form plug-in

开发者 https://www.devze.com 2022-12-08 02:56 出处:网络
I\'m having trouble understanding how to use jQuery and its Form plug-in to access the data returned by an HTTP post operation.

I'm having trouble understanding how to use jQuery and its Form plug-in to access the data returned by an HTTP post operation.

For example, I would like to POST data in a form from a browser, process the data on the server, return a server response (in JSON) to the browser, and display information about that开发者_Go百科 response to the user in an alert -- without rewriting the form.

I thought the following jQuery code would do this:

$(document).ready(function() {
    $('#ajaxFormSubmit').bind('click', function(event) {
        $('#data_entry_form').ajaxSubmit({
            url: "data_entry_ajax",
            dataType: "json",
            success: function(data) {
                alert('Success');
                alert(data.save_status);
            }
        });
    });
});

The server returns the following in JSON object:

{'save_status': 'OK', 'id_number': 2}

But instead of displaying the two alerts over the form and user-entered data, the browser is wiping out the form and displaying the JSON reply.

I thought the "success" value in the options submitted to ajaxSubmit was automatically passed the response received from the server. I've tried various permutations of passing in arguments to the function body (referring to data without passing it in, referring to responseText with and without passing anything in), but these don't work either.

I've looked at "jQuery In Action" to try to understand accessing the response to an xhr object and a .ajax() function, but that hasn't helped either.


Try using jQuery $.post()

<script>
// ...
$('#ajaxFormSubmit').bind('click', function(event) {
  $.post(
    'data_entry_ajax',
    $('#data_entry_form').serialize(),
    function(data) {
      alert('Success');
      alert(data.save_status);
    },
    'json'
  );
});
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号