George_Fal 2016-07-15 23:32 采纳率: 0%
浏览 40

更改回调函数名称

Hi so i have these two functions which get() is a custom ajax request function and you can see that it has two parameters url works fine but the func one which is the callback doesn't seem to change func(serverResponse); to what document.write(serverResponse);. So I was wondering what on earth am I doing wrong? It would be great if one of the kind developers on StackOverflow could help me out really soon. Thank you so much :)

function get(url, func) {
            var xhReq = new XMLHttpRequest();
            xhReq.open("GET", url, false);
            xhReq.send(null);
            var serverResponse = xhReq.responseText;
            func(serverResponse); // Shows "15"
        }

        get('ip.php', 'document.write');
  • 写回答

1条回答 默认 最新

  • weixin_33730836 2016-07-15 23:36
    关注
    get('ip.php', 'document.write');
    

    should be:

    get('ip.php', document.write.bind(document));
    

    The former passes a string; the latter passes a function.

    Perhaps a more typical way to do this sort of thing:

    get('ip.php', function (text) {
        document.write(text);
    });
    
    评论

报告相同问题?