[js]ajax-Heterogeneous Request Jsonp

Source: Internet
Author: User
Tags script tag

Ajax request-Frees each time a manual URL is lost

JS's XMLHttpRequest Object

We use the XMLHttpRequest object to send an AJAX request

Send an AJAX request with XHR

Because I am a webstorm, so I bring my own stereo ha.

That is, this interface http://localhost:63343/web_learn/ajax/ajax/data.txt can be accessed, here we do not manually access it, with Ajax to access.

Here we use AJAX to request this interface and print the content to the console port

<script>    var xhr = new XMLHttpRequest(); //1.创建xhr对象    xhr.open('get', 'http://localhost:63343/web_learn/ajax/ajax/data.txt', true); //2.准备发起url,默认异步true    xhr.onreadystatechange = function () { //3.回来的数据该怎么处理?        if (xhr.readyState === 4 && xhr.status === 200) {            console.log(xhr.responseText);        }    };    xhr.send(null); //4.开始发射</script>

Same-origin access-shorthand URL
<script>    var xhr = new XMLHttpRequest();    xhr.open('get', 'data.txt', true);//这里url可以简写哦,默认代表访问源    xhr.onreadystatechange = function () {        if (xhr.readyState === 4 && xhr.status === 200) {            console.log(xhr.responseText);        }    };    xhr.send(null);</script>
Access to heterogeneous sources

Here we visit http://www.weather.com.cn/data/sk/101010100.html this interface

<script>    xhr = new XMLHttpRequest();    xhr.open('get', 'http://www.weather.com.cn/data/sk/101010100.html', true); //跨站访问不允许Access-Control-Allow-Origin' header    xhr.onreadystatechange = function () {        if (xhr.readyState === 4 && xhr.status === 200){            console.log(xhr.responseText);        }    };    xhr.send(null);</script>

Ajax cross-origin access is not allowed, and the browser does not allow him to do so. It is also for the sake of safety.

Resolving Ajax Heterogeneous Requests

The browser does not allow Ajax to cross-source, but it runs a label cross-origin such as Link script img.

Use the script tag to solve the problem of the heterogeneous source.

We found an interface.

https://suggest.taobao.com/sug?code=utf-8&q=%E5%9B%B4%E5%B7%BE&callback=fn

Discover CLALLBACK=XX He returns you to him, the visible backend gets this parameter (query), and then returns it as part to the front end

Jsonp.html

<!DOCTYPE html>

/GETDATA?CALLBACK=FN part of the implementation of the--NODEJS implementation of this interface

That is, the implementation of what function name, return what

If the FN returns FN (data), the Func is passed, and the Func (data) is returned

App.js we set the function name to Maotai, return Maotai (data)

var http = require (' http '),//Import HTTP URL fs module URL = require (' URL '), FS = require (' FS '); S1 = Http.createserver (functi On (req, res) {//create server var urlobj = Url.parse (Req.url, True),//Accept req Object pathname = urlobj[' pathname '],/ /Remove Pathname in req query = urlobj[' query ']; Get the parameter/getall?cb=maotai "CB//different. html. CSS returns when setting HTTP head different MIME type var reg =/\. (html| css| js| json| Txt| ICO)/I; Regular Judgment MIME type if (reg.test (pathname)) {var suffix = reg.exec (pathname) [1].touppercase ();//mime uniform capitalization ratio var        Suffixmime = null;                switch (suffix) {case "HTML": suffixmime = ' text/html ';            Break                Case "JS": suffixmime = ' text/javascript ';            Break                Case "CSS": suffixmime = ' text/css ';            Break                Case "JSON": suffixmime = ' Application/json ';            Break Case "ICO": Suffixmime = ' ApplicatiOn/octet-stream ';        Break            } try {con = fs.readfilesync ('. ' + pathname);            Res.writehead ($, {' Content-type ': Suffixmime + '; Charset=utf-8 '});        Res.end (con);            } catch (E) {Res.writehead (404, {' Content-type ': ' Text/plain;charset=utf-8 '});        Res.end ("File Not Found")}} if (pathname = = = = "/getall") {var fnname = query["CB"];//Get Cb=maotai        con = Fs.readfilesync ('./data.txt ', ' utf-8 ');        Con = ' A, b ';        Res.writehead ($, {' Content-type ': ' Application/json;charset=utf-8 '}); Res.end (FnName + ' (' + con + ', 22) '); End returns Maotai (A,B,22)}), S1.listen (1234, function () {Console.log ("Http://127.0.0.1:1234/getall?cb=maotai");}) ;

Start the Nodejs service side

Implement this interface

http://127.0.0.1:1234/getall?cb=maotai

return results

Trigger page

<script>    var a = 12;    var b = 13;    function maotai(a,b,num) {        console.log(a,b,num);    }</script><!--//jsonp可以返回任意格式字符串,但一般返回的是json格式字符串--><script type="text/javascript" src="http://127.0.0.1:1234/getall?cb=maotai"></script>

Access the results of the return.

[js]ajax-Heterogeneous Request Jsonp

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.