小编典典

将返回值从php传递给js

ajax

我有3个文件main.php,action.js和ajax.php,我在javascript文件中通过ajax调用成功地将某些div单击的内容从main.php更改为ajax.php的内容。看起来像这样:

var value = $(this).attr("id");

$.ajax({
    type: 'get',
    url: "ajax.php",
    data: {
        auto_value: value
    },
    success: function(response) {
        $('.gridnr1, .textnr1').fadeOut(400, function(){
            $('.textnr2, .gridnr2').fadeIn(400);
        });

        var newtextcaption = $(response).filter('#newtextcaption').html();
        var box = $(response).filter('#box').html();

        $('#textnr2').html(newtextcaption);
        $('#gridnr2').html(box);

        for (var i=0; i<VALUE_FROM_AJAXphp; i++) {
            DO SOMETHING WITH i;
        }
    });

现在,我需要从action.js中的ajax.php中的函数返回值,因为我想迭代直到该值(请参见上面的代码)。如何将此值从ajax.php传递到action.js。我很困惑我需要什么来获取值ajax?,json?或者是其他东西?

谢谢。


阅读 379

收藏
2020-07-26

共1个答案

小编典典

成功函数中的响应就是您从PHP中获得的回报。因此发送JSON最简单,因为这样您的响应就只是一个对象。

可以说ajax.php返回此JSON

{
    "newtextcaption": "whatever the text is",
    "boxhtml": "whatever your box html is",
    "AjaxValue": 4389489473289
}

那么你的成功功能应该是

 success: function(response) {
                $('.gridnr1, .textnr1').fadeOut(400, function(){
                    $('.textnr2, .gridnr2').fadeIn(400);
                });

                var newtextcaption = response.newtextcaption;
                var box = response.boxhtml;

                $('#textnr2').html(newtextcaption);
                $('#gridnr2').html(box);

                for (var i=0; i<response.AjaxValue; i++) {
                     DO SOMETHING WITH i;
                }
2020-07-26