Tp5 application/json 跨域问题

1,普通的请求,加这个就好了

比如默认的 application/x-www-form-urlencoded

header("Access-Control-Allow-Origin: *");

2,如果是application/json

需要补加

header("Access-Control-Allow-Origin: *");

header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");

header("Access-Control-Allow-Headers:x-requested-with, Referer,content-type,token,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");

3,测试案例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	 <script src="./jquery-3.4.1.min.js"></script>
</head>
<body>
	
	<h1></h1>
	<input type="button" value="点击获取数据" id="clickButton" crossOrigin="anonymous"> 
	<!--
	<form action="./jquery-3.4.1.min.js" method="post" enctype="multipart/form-data">
	<h1>post</h1>
		ID:<input id="username" type="text" name="username" />
		Password:<input id="password" type="password" name="password" />
		<input type="submit" value="Submit" />
	</form>
	<h1></h1>
	<form action="./jquery-3.4.1.min.js" method="get" enctype="multipart/form-data">
	<h1>get</h1>
		ID:<input id="username" type="text" name="username" />
		Password:<input id="password" type="password" name="password" />
		<input type="submit" value="Submit" />
	</form>
	-->
</body>
</html>
<script>

//$(".clickButton").click({
$(document).on(click,"#clickButton",function(){
	var url="http://192.168.20.98:1001/admin/api/nrfstatus";
	var obj = {"status": "3","gnb_array": ["gnb1"]};
    $.ajax({
        url:url,
		data: JSON.stringify(obj),
        type : "post",   //请求类型
        dataType:json,
		contentType: application/json,
        success:function(res){

            console.log(res);
        }
    })
});
    
</script>

效果

当然在nginx加上也行,这里为了方便直接在项目框架加上了。

经验分享 程序员 微信小程序 职场和发展