简体   繁体   中英

get file_get_contents with from php function with ajax

i have to get the html reply of two php function with AJAX

Here my code

Home.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>

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

what's wrong here ? I can not see the results.

file_get_contents() is for reading a file or URL into a string. You don't need to use these if you're creating the content in your script. Just have your functions return strings.

function loopone() {
    $result = "";
    for (a = 0; $a < 10; $a++) {
        $result .= "<div class='mydiv'>$a</div>";
    }
    return $result;
}
function casetwo() {
    global $a, $g;
    if ($a != $g) {
        return "<div id='mydiv2'>$a</div>";
    } else {
        return "";
    }
}

$prew1 = loopone();
$prew2 = casetwo();
echo json_encode(array("reply1"=>$prew1, "reply2"=>$prew2));

I changed id="mydiv" to class="mydiv" because IDs are supposed to be unique, you shouldn't return the same ID in a loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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