猿问

使用ajax从php函数中获取file_get_contents

我必须使用 AJAX 获取两个 php 函数的 html 回复


这是我的代码


主页.php


<script>

    $( document ).ready(function(){

        var parameter = {

            "mynumber" : $('#mynumber').val()

    };

    $.ajax({

            data:  parameter , 

            url:   'script.php', 

            type:  'post',

            dataType: 'json',

            beforeSend: function () {

                    $("#loading").show();

            },

            success:  function (response) { 

                    $("#loading").hide();

                    $("#div1").html(response.reply1);                        

                    $("#div2").html(response.reply2);                        

            },                

    });   });

    </script>

和脚本.php


function loopone(){

     for($a=0;$a<10;$a++){

          ?><div id="mydiv"><?php echo $a;?></div>

     }

}

function casetwo(){

     if($a<>$g){

          ?><div id="mydiv2"><?php echo $a;?></div>

     }

}


$prew1=file_get_contents(loopone());

$prew2=file_get_contents(casetwo());

$reply1=prew1;

$reply2=prew2;

echo json_encode(array("reply1"=>$reply1, "reply2"=>$reply2));

这里有什么问题?我看不到结果。


宝慕林4294392
浏览 223回答 1
1回答

浮云间

file_get_contents()用于将文件或 URL 读入字符串。如果您在脚本中创建内容,则不需要使用这些。只需让您的函数返回字符串即可。function loopone() {&nbsp; &nbsp; $result = "";&nbsp; &nbsp; for (a = 0; $a < 10; $a++) {&nbsp; &nbsp; &nbsp; &nbsp; $result .= "<div class='mydiv'>$a</div>";&nbsp; &nbsp; }&nbsp; &nbsp; return $result;}function casetwo() {&nbsp; &nbsp; global $a, $g;&nbsp; &nbsp; if ($a != $g) {&nbsp; &nbsp; &nbsp; &nbsp; return "<div id='mydiv2'>$a</div>";&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return "";&nbsp; &nbsp; }}$prew1 = loopone();$prew2 = casetwo();echo json_encode(array("reply1"=>$prew1, "reply2"=>$prew2));我换id="mydiv"到class="mydiv",因为标识都应该是独一无二的,你不应该在一个循环中返回相同的ID。
随时随地看视频慕课网APP
我要回答