jQuery - 一旦AJAX完成就做一些事情

时间:2013-10-25 12:57:49

标签: javascript jquery ajax post

我有一个简单的POST AJAX调用 - 一旦完成我想运行一个自定义函数 - 我试过.success()没有任何喜悦 - 有人可以帮助我吗?

jQuery.post('http://www.site.com/product/123/', jQuery('#product_addtocart_form').serialize(), function() 
   // on success - do something here
});

4 个答案:

答案 0 :(得分:3)

您可以根据$.ajax()

中的要求使用以下任何回调
 .done(function() {
    alert( "success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );
  });

答案 1 :(得分:2)

你可以这样做:

$.post(url, data, function () {
    alert("success");

    // Call the custom function here
    myFunction();
});

或者这个:

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post(url, data);

jqxhr.done(function () {
    alert("second success");
    // Call the custom function here
    myFunction();
});

答案 2 :(得分:1)

试试你的ajax电话:

<script>
    $.ajax({
        type: "POST",
        url: "./WebServices/MethodName",
        data: "{someName: someValue}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var row = response.d;
            if (row.length > 0) {
                $.each(row, function (index, item) {
                });
            }
            else {
                $("#").html("No Rows Found");
            }
        },
        failure: function () {
        }
    });
</script>

答案 3 :(得分:1)

.ajax的基本用法如下所示:

<强> HTML

<form id="foo">
 <label for="bar">A bar</label>
 <input id="bar" name="bar" type="text" value="" />
 <input type="submit" value="Send" />
</form>

<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>

<强>的JavaScript

/* Attach a submit handler to the form */
$("#foo").submit(function(event) {

/* Stop form from submitting normally */
event.preventDefault();

/* Clear result div*/
$("#result").html('');

/* Get some values from elements on the page: */
var values = $(this).serialize();

/* Send the data using post and put the results in a div */
$.ajax({
    url: "test.php",
    type: "post",
    data: values,
    success: function(){
        alert("success");
        $("#result").html('Submitted successfully');
    },
    error:function(){
        alert("failure");
        $("#result").html('There is error while submit');
    }
  });
});