将数据从一个Ajax传递到另一个Ajax中

时间:2017-07-26 13:28:49

标签: jquery

$.ajax({
    url: "/Kostas/measurementData.php",
    type: "POST",
    data: {UserID: <?php echo json_encode($UserID); ?>, MeasurementID: selected},
    success: function (data) {
        $.ajax({
            url: "/Kostas/measurementData.php",
            type: "POST",
            data2: {UserID: <?php echo json_encode($UserID); ?>, MeasurementID: 2},
            success: function (data, data2) {
                console.log(data);
                console.log(data2);

            },
            error: function (data) {
               console.log("error 2");
            } 
        });

    },
    error: function (data) {
       console.log("error 1");
    }
});

我想要做的是在第二个函数中处理数据data2,但控制台日志没有显示数据已被填充。我该如何解决这个问题? 更新: 添加了错误console.log,它命中了错误2

为我的代码量身定制的答案,供其他人以后参考

$.ajax({
    url: "/Kostas/measurementData.php",
    type: "POST",
    data: {UserID: <?php echo json_encode($UserID); ?>, MeasurementID: selected},
    success: function (data) {
        $.ajax({
            url: "/Kostas/measurementData.php",
            type: "POST",
            data: {UserID: <?php echo json_encode($UserID); ?>, MeasurementID: 2},
            success: function (data2) {
                console.log(data);
                console.log(data2);

            },
            error: function (data2) {
                console.log("error 2");
            }
        });

    },
    error: function (data) {
        console.log("error 1");
    }
});

1 个答案:

答案 0 :(得分:1)

在第二个data中重命名success。第一个data仍然在范围内,可以在第二个success

中访问
$.ajax({
    //.....
    success: function (data) {
        $.ajax({
            //.....
            success: function (data2) {
                console.log(data);// data from first request
                console.log(data2);// data2 from second request

            },
             //.....
        });

    },
    //.....