1、vue中引入jquery,组件中的代码如下
<template>
<div>
1、ajax jsonp跨域
2、PHP后台验证header头信息
</div>
</template>
<script>
import querystring from 'querystring'
export default {
name: 'jsonp',
created() {
$.ajax({
url: 'http://localhost/tencent/jsonp/index.php',
type: 'post',
dataType: 'jsonp',
data: {
name: "xiaoming",
id: '001'
},
success: function (data) {
console.log(data)
},
error: function (data) {
console.log(data);
}
});
}
}
</script>
2、PHP后端代码,注意是GET方式,jsonp只有get方式
<?php
$name = $_GET['name'];
$id = $_GET['id'];
$callback = $_GET['callback'];
////指定允许其他域名访问
//header("Access-Control-Allow-Origin:*");
//// 响应类型
//header("Access-Control-Allow-Methods:POST,GET,PUT,DELETE,OPTIONS");
//// 响应头设置
//header("Access-Control-Allow-Headers:x-requested-with,content-type");
//
//header('Access-Control-Allow-Headers:TOKEN,test');
header("Content-Type:application/x-www-form-urlencoded,charset=utf-8");
if (true) {
$data = array(
'name' => $name,
'id' => $id,
'msg'=>'返回成功'
);
$jsondata = json_encode($data);
// echo $jsondata;
// exit($callback."($jsondata)");
echo $callback."(".$jsondata.")";
} else {
$data = array(
'msg' => '请求不合法',
);
$jsondata = json_encode($data);
// echo $jsondata;
// exit($callback . "($jsondata)");
echo $callback."(".$jsondata.")";
}
?>