Two $.post requests one after the other.Second $.p

2018-12-31 14:43发布

I have a javascript function inside which i have two $.post requests.Both the $.post requests should get executed.But sometimes,second $.post request doesn't get executed.What could be the reason for it?

标签: ajax jquery
1条回答
几人难应
2楼-- · 2018-12-31 15:07

$.post() is an abbreviated form of the $.ajax() structure. I usually prefer to use the $.ajax() structure because:

  • It's easier to see if I've missed anything
  • I can more easily add additional params, such as asynch: false,
  • When new to ajax I found it considerably easier to troubleshoot this structure

In your case, you might find your problem easier to solve in a $.ajax() structure, since it would be easier to see that a second ajax call (that depends on the outcome of a first ajax call) must happen in the success function of the first ajax call.

Here is a standalone example (too bad jsFiddle cannot handle ajax...):

TESTER.PHP

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function() {
                $('#eml').focus();

                $('#mybutt').click(function() {
                    var $a = $('#eml').val();
                    var $b = $('#pw').val();

            //alert('Email: ' +$a+ '     Pass: ' +$b);

                    $.ajax({
                        type:"POST",
                        url: "yourphpfile.php",
                        data: 'email=' +$a+ '&pass=' +$b,
                        success: function(data) {
            alert(data);
                            var aData = data.split('|');

                            var name = aData[0];
                            var code = aData[1];
            alert('Name: ' +name+ '     Code: ' +code);

                            $.ajax({
                                type:"POST",
                                url: "yourphpfile.php",
                                data: 'name=' +name+ '&code=' +code,
                                success: function(newdata) {
                                    alert(newdata);
                                } //END success_ajax2
                            }); //END ajax() #2

                        } //END success_ajax1
                    }); //END ajax() #1
                }); //END mybutt.click()

            }); //END $(document).ready()

        </script>
    </head>
<body>

    Email: <br />
    <input type="text" id="eml" /><br />
    Password: <br />
    <input type="password" id="pw" /><br />
    <input type="button" id="mybutt" value="Submit">

</body>
</html>

yourphpfile.php

<?php

if (isset($_POST['email'])) {
    $e = $_POST['email'];
    $p = $_POST['pass'];

    $name = 'Bob';
    $code = '1234';

    $resp = $name .'|'. $code;
    echo $resp;

}else if (isset($_POST['name'])) {
    $n = '<h1>Here is something new</h1>';
    echo $n;
}
查看更多
登录 后发表回答