douliexing2195 2014-05-18 13:38
浏览 36
已采纳

我的ip-address功能不起作用[关闭]

My script:

$(function () {
    $("h2").text($.get("ajax.getIp.php",function(data){ return data; }));
});

and my ajax.getIp.php:

<?php$_SERVER['REMOTE_ADDR']?>

It will say [object Object] in the h2 how can I solve this?

  • 写回答

3条回答 默认 最新

  • dongxiegao3071 2014-05-18 13:45
    关注

    Use the success handler, not the return value

    Functions like $.get work with callbacks; the return value is not the response from the server - it's the xhr object.

    > $.get()

    Object {readyState: 1, setRequestHeader: function, getAllResponseHeaders: function, getResponseHeader: function, overrideMimeType: function…}

    See the docs for examples of how to use $.get:

    $.get( "ajax/test.html", function( data ) {
      $( ".result" ).html( data ); # <-
      alert( "Load was performed." );
    });
    

    Note that in the success handler is where the contents of .result are updated. Applied to the code in the question that would be:

    $.get( "ajax.getIp.php", function( data ) {
      $("h2").text( data );
    });
    

    The php code isn't echoing an ip address

    The output of a php file with these contents:

    <?php$_SERVER['REMOTE_ADDR']?>
    

    Is the string:

    <?php$_SERVER['REMOTE_ADDR']?>

    Because, there isn't any php code in it - <?phpnospace does not start a php block. To output the client's IP use the code:

    <?php echo $_SERVER['REMOTE_ADDR']?>
    

    Note the whitespace and echo statement, or

    <?= $_SERVER['REMOTE_ADDR']?>
    

    (If using php 5.4 OR earlier versions with php short tags enabled) - in this case the whitespace is optional.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?