简体   繁体   English

将返回值从 php 传递给 js

[英]Pass a return value from php to js

I have 3 files main.php, action.js and ajax.php and i successfully changed the content on click of some divs from main.php to some of ajax.php with a ajax call in my javascript file.我有 3 个文件 main.php、action.js 和 ajax.php,我成功地将点击某些 div 的内容从 main.php 更改为某些 ajax.php,并在我的 javascript 文件中调用了 ajax。 It looks like this:它看起来像这样:

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;
        }
    });

Now i need a return value from a function in ajax.php in my action.js because I want to iterate till this value (see the code above).现在我需要一个来自 action.js 中 ajax.php 函数的返回值,因为我想迭代到这个值(见上面的代码)。 How to pass this value from the ajax.php to the action.js.如何将此值从 ajax.php 传递到 action.js。 I am confused what do I need to get the value ajax?, json?我很困惑我需要什么才能获得值 ajax?,json? or something else?或者是其他东西?

Thank you.谢谢你。

in the success function, response, is what you get back from the PHP.在成功函数中,响应是您从 PHP 返回的内容。 so sending JSON would be easiest, because then your response is just an object.所以发送 JSON 将是最简单的,因为那样你的响应只是一个对象。

Lets say ajax.php returns this JSON让我们说 ajax.php 返回这个 JSON

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

then your success function should be那么你的成功函数应该是

 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;
                }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM