簡體   English   中英

我如何使用jquery ajax在同一個文件中發送多個請求並在php中獲取所需的響應

[英]How do i send multiple requests for the same file and get the required response back in php using jquery ajax

var postID = $post->ID;
$.ajax({
             type: "POST",
             url: "<?php echo get_template_directory_uri();?>/b.php",
             data:{postID:postID},
             dataType: 'json',
             success: function(result){
                if(result!=''){
                    r = $.parseJSON(result);
                    final_rating = get_final_rating(r);
                    set_stars(final_rating);
                }
            }
        });

var arr = [a,b,c,d,e,f];
$.ajax({
                 type: "POST",
                 url: "<?php echo get_template_directory_uri();?>/b.php",
                 data:{star:arr, postID:postID},
                 async :false,
                 cache: false,
                 success: function(result){
                        if(result === '1')
                        {
                            final_rating = result;
                            set_stars(final_rating);
                        }
                    }
                });

您可以使用jQuery執行以下操作:

var postID = <?php echo $post->ID; ?>,
    arr = [a,b,c,d,e,f],
    req1, req2;

req1 = $.ajax({
    type: "POST",
    url: "<?php echo get_template_directory_uri();?>/b.php",
    data: {postID:postID},
    dataType: 'json'
});

req2 = $.ajax({
    type: "POST",
    url: "<?php echo get_template_directory_uri();?>/b.php",
    data: {star:arr, postID:postID},
    async: false,
    cache: false
});

$.when(req1, req2).then(function (data1, data2) {

    // data1[0] = result

    if(data1[0] !== '') {
        r = $.parseJSON(result);
        final_rating = get_final_rating(r);
        set_stars(final_rating);
    }

    // data2[0] = result

    if(data2[0] === '1') {
        final_rating = result;
        set_stars(final_rating);
    }

});

var postID = $post->ID; 應替換為:

var postID = <?php echo $post->ID; ?>;

您也做錯了Ajax。 您應該在admin-ajax.php - http: admin-ajax.php上發出所有請求

然后,您可以使用不同的action參數來區分不同的Ajax調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM