Skip to content
On this page

ajax&jsonp 手写实现

js
// 客户端
function _jsonp(params) {
    let url = `${params.url}&callback=${params.cb.name}`
    let script = document.createElement('script')
    // script.type = 'text/javascript'
    script.src = url
    let head = document.getElementsByTagName('head')[0]
    head.appendChild(script)
}

function cb(res) {
    console.log(res)
}

_jsonp({
    url: 'http://localhost:8090/info?',
    cb
})

// 服务端实现——express版
const express = require('express')
const app = express()
app.listen(8090)
app.get('/info', (req, res) => {
    let {callback} = req.query // json格式的query
    res.send(`${callback}(${66666})`)
})

// 服务端实现——Koa版
const Koa = require('koa')
const app = new Koa()
app.listen(8090)
app.use(ctx => {
    let {callback} = ctx.request.callback // json格式的query
    ctx.body = `${callback}(${6666})`
})
// 客户端
function _jsonp(params) {
    let url = `${params.url}&callback=${params.cb.name}`
    let script = document.createElement('script')
    // script.type = 'text/javascript'
    script.src = url
    let head = document.getElementsByTagName('head')[0]
    head.appendChild(script)
}

function cb(res) {
    console.log(res)
}

_jsonp({
    url: 'http://localhost:8090/info?',
    cb
})

// 服务端实现——express版
const express = require('express')
const app = express()
app.listen(8090)
app.get('/info', (req, res) => {
    let {callback} = req.query // json格式的query
    res.send(`${callback}(${66666})`)
})

// 服务端实现——Koa版
const Koa = require('koa')
const app = new Koa()
app.listen(8090)
app.use(ctx => {
    let {callback} = ctx.request.callback // json格式的query
    ctx.body = `${callback}(${6666})`
})