将返回值从php传递给js

时间:2016-09-19 21:00:52

标签: javascript php jquery json ajax

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

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?或其他什么?

谢谢。

1 个答案:

答案 0 :(得分: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;
                }