How to get data with JavaScript from another server?

前端 未结 8 628
生来不讨喜
生来不讨喜 2020-12-02 17:23

How can I make requests to other server(s) (i.e. get a page from any desired server) with a JavaScript within the user\'s browser? There are limitations in place to prevent

8条回答
  •  广开言路
    2020-12-02 18:27

    This is rather easy... if you know the 'secret' trick almost nobody shares..

    It's called Yahoo yql...

    So in order to regain 'power to the user' (and returning to the convenient mantra: 'never accept no'), just use http://query.yahooapis.com/ (instead of a php? proxy serverside script).
    jQuery would not be strictly needed.

    EXAMPLE 1:
    Using the SQL-like command:

    select * from html 
    where url="http://stackoverflow.com" 
    and xpath='//div/h3/a'
    

    The following link will scrape SO for the newest questions (bypassing cross-domain security bull$#!7):
    http://query.yahooapis.com/v1/public/yql?q=select%20title%20from%20html%20where%20url%3D%22http%3A%2F%2Fstackoverflow.com%22%20and%0A%20%20%20%20%20%20xpath%3D%27%2F%2Fdiv%2Fh3%2Fa%27%0A%20%20%20%20&format=json&callback=cbfunc

    As you can see this will return a JSON array (one can also choose xml) and calling the callback-function: cbfunc.

    Indeed, as a 'bonus' you also save a kitten every time you did not need to regex data out of 'tag-soup'.

    Do you hear your little mad scientist inside yourself starting to giggle?

    Then see this answer for more info (and don't forget it's comments for more examples).

    Good Luck!

提交回复
热议问题